2017-09-04 58 views
0

對於一個固定的,透明的菜單按鈕(在position:fixed;菜單)我要實現以下目標:CSS/JavaScript:根據其當前背景更改元素類?

  • 如果按鈕上徘徊,一個最黑暗的背景,使之變白。
  • 如果按鈕懸停在大多數明亮的背景上,則將其設爲黑色。

聽起來很簡單,但似乎很複雜。

我發現下面的庫:​​

問題:

  • 僅適用於圖像,幾乎爲背景圖像
  • 不適用於非圖像背景的工作

我已經閱讀了很多關於CSS Blend模式的文章(https://css-tricks.com/basics-css-blend-modes/),但我真的無法弄清楚他們如何能夠幫助我即使這種簡單的行爲。

我也讀過,canvas元素可能會幫助,但我不知道爲什麼。

這是我的僞代碼:

$(document).scroll(function() { 
    check_bg_for_el(); 
}); 

function check_bg_for_el() { 
    if(hasDarkBackground($('#myel'))) { 
     $(this).addClass('dark-bg'); 
    } else { 
     $(this).addClass('light-bg'); 
    } 
} 

function hasDarkBackground(el) { 
    // ???? 
} 

你對這個怎麼可能實現任何想法?

+0

你試過Window.getComputedStyle? –

+0

@OlegYudovich這可以幫助我嗎? – Blackbam

+0

你想知道圖像是黑暗還是光線?或者如何使黑暗的圖像燈和其他方式? – Blindman67

回答

0

我爲您創建了一個可重用的函數。 您可以更改任何CSS屬性(使用其對應的JS作爲參數傳遞)。示例CSS background-color =>backgroundColor

顏色必須以rgb格式傳遞,由window.getComputedStyle()返回。

let changeDomCond = (source, target, condProp, condPropValue, newPropValue) => { 
 
    let sourceDom = document.getElementById(source); 
 
    let targetDom = document.getElementById(target); 
 
    let style = window.getComputedStyle(sourceDom); 
 
    if (style[condProp] === condPropValue) { 
 
    targetDom.style[condProp] = newPropValue; 
 
    } 
 
}; 
 

 
    let btn = document.getElementById('btn'); 
 
    btn.addEventListener('click', e=> { 
 
    changeDomCond('bkg1', 'a', 'backgroundColor', 'rgb(255, 0, 0)', 'rgb(100, 100, 200)'); 
 

 
changeDomCond('bkg2', 'b', 'backgroundColor', 'rgb(255, 255, 0)', 'rgb(255, 150, 255)'); 
 
    });
#bkg1 { 
 
    width: 250px; 
 
    height: 100px; 
 
    background-color: rgb(255, 0, 0); 
 
} 
 

 
#bkg2 { 
 
    width: 250px; 
 
    height: 100px; 
 
    background-color: rgb(255, 255, 0); 
 
} 
 

 
#a, 
 
#b { 
 
    position: absolute; 
 
    width: 50px; 
 
    height: 50px; 
 
    background-color: orange; 
 
}
<button id="btn">Click here to change color conditionally</button> 
 
<div id="bkg1"> 
 
    <div id="a"> 
 
    Hello 1 
 
    </div> 
 
</div> 
 

 
<div id="bkg2"> 
 
    <div id="b"> 
 
    Hello 2 
 
    </div> 
 
</div>