2011-08-31 21 views

回答

1

這是可能的,但只有在現代瀏覽器(鉻,Safari,火狐,歌劇)。

您將需要有兩個<div>

像這樣..

<div class="container"> 
    <div class="revealer"></div> 
</div> 

和CSS像這樣

.container { 
    position: relative; 
    background: url("images/your-background.jpg"); 
} 
.revealer { 
    position: absolute; 

    //set the mask size to be the size of the container 
    top: 0; 
    left: 0; 
    bottom: 0; 
    right: 0; 

    z-index: 1; 
    background: url("images/your-background-over-state.jpg"); 

    //css3 image masks, this is not cross browser, see the demo for 
    // cross browser syntax 
    mask: url("images/mask-shape.png") no-repeat; 

    //make sure the mask is off screen at first, by setting the mask position 
    //to minus the width and height of your mask image 
    mask-position: -300px -300px   
} 

而且JS

window.addEventListener('load',function(){ 
    var background = document.querySelector('.container'), 
     revealer = document.querySelector('.revealer'); 

    background.addEventListener('mousemove', function(e){ 

     //the minus represents the half the width/height of your mask image 
     // to make the reveal centred to the mouse. 
     var x = e.offsetX - 150, 
      y = e.offsetY - 150; 

     // move the position of the mask to match the mouse offsets  
     revealer.style.maskPosition = x+'px '+y+'px'; 

     return false; 
    }); 


}); 

因爲您需要確保.container中的任何其他內容具有比掩碼更高的z-index,以確保內容未被屏蔽。要做到這一點相對定位添加到元件在容器

像這樣

.container *:not(.revealer) { 
    position: relative; 
    z-index: 2; 
} 
在面罩使用

圖像是其中固體色創建可見或填充區的圖像,並且所述透明區域是掩模或剪下。

Demo with cross browser code

+0

我很想擺弄你的代碼,但沒有效果輸出jsfiddle? – Northernlights

+0

你使用什麼瀏覽器?在Chrome中嘗試它,我在Firefox中測試,似乎它不支持新的CSS屬性。 – AshHeskes

+0

我在firefox上,現在在家裏使用chrome和jsfddle的詞語,但是上帝,現在對我來說很複雜。不過謝謝你,我會努力一點 – Northernlights

2

你可以通過使用一個透明的png圖像來做到這一點,該圖像是從中心透明到邊緣半透明的徑向漸變,並使其跟隨鼠標。

document.onmousemove=mousefollower 
function mousefollower(e){ 
    x = (!document.all)? e.pageX : event.x+document.body.scrollLeft; 
    y = (!document.all)? e.pageY : event.y+document.body.scrollTop; 
    document.getElementById('myImage').style.left = x + 'px'; 
    document.getElementById('myImage').style.top = y + 'px'; 
} 

很明顯,您也可以使用jQuery,並設置mousemove函數只發生在特定的div上。還要確保您使用的圖像足夠大(至少是尺寸的兩倍),以便在移動到div遠端時不會顯示邊緣(這意味着對於大面積區域,您將需要一個巨大的圖像它可能會有很大的滯後)。將圖像放入div中,並將溢出設置爲none,以剪切掉區域外的任何東西。

+0

這不會達到同樣的效果。它只會提供一個半透明的圓圈來跟隨鼠標。它不會透露它背後的元素的一部分。 – AshHeskes

+0

這是沿着正確的路線。透明png需要是複雜設計被咬住的那個。然後你需要一個跟在鼠標後面的圖像_behind_,這個圖像是從中心到白色的淡入淡出。我懷疑用一些聰明的javascript也會有一種「畫布」方式來實現這一點。 – MrMisterMan

+0

這將會類似於一些jQuery的縮放腳本,是的?如果你們可以指出一個我可以修補的例子,那將是完美的。我的JS並不是那個忍者。 – Northernlights

3

這可以很容易地使用JavaScript的一些CSS和背景定位。這裏有兩個例子:http://jsbin.com/ococal/3

源代碼很容易理解,你可以開始解決這個問題。

+0

的其餘部分變暗,這要歸功於簡化。 – Northernlights

+0

結束了,只是應用一個白色的陰影邊框打破了一點 – Northernlights

相關問題