我想弄清楚如何有一个事件监听器改变类的多个项目堆叠在彼此的顶部。
我有一个当前的小提琴在这里,我正在工作,基本上当有人点击按钮和悬停一个对象它改变对象的类悬停。我想更进一步,这样当两个物体被放置在彼此的顶部时,两个物体都会受到影响。有简单的方法吗?
当前,当你点击并悬停它只影响最上面的元素。我想同时影响top和bottom元素。任何帮助将非常感激!
http://jsfiddle.net/Ltdgx363/1/obj=document.getElementsByTagName("object");
var mouseDown = 0;
document.onmousedown = function() {
++mouseDown;
}
document.onmouseup = function() {
--mouseDown;
}
for(i = 0; i < obj.length; i++) {
obj[i].addEventListener("mouseover", colorred ,false);
}
function colorred(){
if(mouseDown>0){
this.className = "red";
}
}
假设我理解你的问题正确,你可以用jQuery parent()
和children()
做到这一点。看我的小提琴:http://jsfiddle.net/yu404vf2/2/
你的函数基本上变成了:
function colorred(){
if(mouseDown>0){
this.className = "red";
}
$(this).parents().class = "red";
}
如果对象的堆叠方式如下:
<object id="object3">Test3
<object id="object4">Test4</object>
</object>
但如果对象由于z-index
/position absolute而堆叠,则不
如果你需要鼠标指针下面的对象,javascript中有一个很好的函数叫做elementFromPoint
,你可以像这样使用:
var x = event.clientX, y = event.clientY,
elementMouseIsOver = document.elementFromPoint(x, y);
elementMouseIsOver.class="red";
更新jsfiddle: http://jsfiddle.net/yu404vf2/5/
希望对你有帮助。
有很多方法可以做到这一点,但是假设您不想使用库。我已经更新了你的jsfiddle,但在这里添加了评论。
//find all objects, and create an empty array, to contain the object id's later on.
var r_objects = document.getElementsByTagName('object');
var r_ids = [];
/*
your colorred function,
not using your general mousedown tracker,
but added the mousedown eventListener to your objects.
*/
var colorred = function(obj,addClass){
/*
find the index of your currently clicked element,
to determine if there are any "underneath" it, objects
that are rendered earlier, get a lower index.
*/
oIndex = r_ids.indexOf(obj.id);
/*
loop through the indexes lower and the same as the element
your mouse is on. you can determine the depth here, by not looping
through, but by simply subtracting or adding to the oIndex var, and
using it as a key in your r_objects array. addClass is true or false,
depending on the event, so it also removes the class after your
mouseup event is triggered
*/
for(i = 0; i <= oIndex; i++){
affectedObj = r_objects[i];
if(addClass){
affectedObj.className = "red";
}else{
affectedObj.className = "";
}
};
};
var addListeners = function(){
for(i = 0; i < r_objects.length; i++){
obj = r_objects[i];
obj.addEventListener('mousedown',function(){
colorred(this,true);
});
obj.addEventListener('mouseup',function(){
colorred(this,false);
});
//add the id to the r_ids array
r_ids.push(obj.id);
};
};
addListeners();
http://jsfiddle.net/Ltdgx363/3/您可以通过使用for循环来确定受影响元素的"深度"。