我有这个功能,但有两个问题我无法解决,第一个是鼠标操作设置在所有屏幕上,我希望它只是悬停在潜水“ehab”上,而不是当我将鼠标移到屏幕上, 另一个问题是,当我有多个div时,该功能仅适用于第一个... 请告诉我
/*
By : Ofelquis
Twitter: @felquis
Blog : tutsmais.com.br
Simples implementação ;)
*/
!(function ($doc, $win) {
var screenWidth = $win.screen.width / 2,
screenHeight = $win.screen.height / 2,
$ehab = $doc.querySelectorAll('#ehab')[0],
validPropertyPrefix = '',
otherProperty = 'perspective(600px)';
if(typeof $ehab.style.webkitTransform == 'string') {
validPropertyPrefix = 'webkitTransform';
} else {
if (typeof $ehab.style.MozTransform == 'string') {
validPropertyPrefix = 'MozTransform';
}
}
$doc.addEventListener('mousemove', function (e) {
// vars
var centroX = e.clientX - screenWidth,
centroY = screenHeight - (e.clientY + 13),
degX = centroX * 0.1,
degY = centroY * 0.1
// Seta o rotate do elemento
$ehab.style[validPropertyPrefix] = otherProperty + 'rotateY('+ degX +'deg) rotateX('+ degY +'deg)';
});
})(document, window);
答案 0 :(得分:2)
第一个问题,(我希望它在悬停div"#ehab" 时),你需要将mousemove
事件附加到你的div:
$ehab.addEventListener('mousemove', function (e) {
//You code here.
});
第二个问题,(当我有多个div时,该功能只适用于第一个),你不能在DOM树上有重复的ID,更改选择器对于一个类,例如,.ehab
然后你必须遍历匹配的元素,请尝试这个代码:
/*
By : Ofelquis
Twitter: @felquis
Blog : tutsmais.com.br
Simples implementação ;)
*/
!(function($doc, $win) {
var $ehabDIVs = $doc.querySelectorAll('.ehab'),
otherProperty = 'perspective(600px)';
for (var i = 0; i < $ehabDIVs.length; ++i) {
var $ehab = $ehabDIVs[i];
$ehab.addEventListener('mousemove', function(e) {
// vars
var centroX = (e.pageX - this.offsetLeft) - this.offsetWidth/2,
centroY = this.offsetHeight/2 - (e.pageY-this.offsetTop),
degX = centroX * 0.1,
degY = centroY * 0.1
if(this._leave) clearInterval(this._leave);
// Seta o rotate do elemento
this.style.transform = otherProperty + 'rotateY(' + degX + 'deg) rotateX(' + degY + 'deg)';
});
$ehab.addEventListener('mouseleave', function(e) {
var self = this;
this._leave = setTimeout(function() {
self.style.transform = 'rotateY(0deg) rotateX(0deg)';
}, 250);
});
}
})(document, window);
&#13;
.ehab {
width:300px;
height:300px;
background-color:red;
margin:15px;
float:left;
transition: transform 0.15s ease;
}
&#13;
<div class="ehab">First Div</div><div class="ehab">Second Div</div>
&#13;
祝好运Ismaiel。