我正在试图找出如何让一个事件列表器更改多个彼此叠加的项目的类。
我在这里有一个当前的小提琴,我正在努力,基本上当有人点击按钮并悬停一个对象时,它会改变悬停的对象的类。我想更进一步,以便当两个物体位于彼此的顶部时,两个物体都将受到影响。有一个简单的方法吗?
目前,当您单击并悬停时,它仅影响最顶层的元素。我想影响顶部和底部元素。任何帮助将不胜感激!
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";
}
}
答案 0 :(得分:1)
假设我理解你的问题是正确的,你可以使用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
/位置绝对而堆叠了对象,则不会。
如果您需要鼠标指针下方的对象,javascrtipt中有一个名为elementFromPoint
的函数,您可以使用它:
var x = event.clientX, y = event.clientY,
elementMouseIsOver = document.elementFromPoint(x, y);
elementMouseIsOver.class="red";
更新了jsfiddle:http://jsfiddle.net/yu404vf2/5/
希望有所帮助。
答案 1 :(得分:0)
有很多方法可以做到这一点,但假设您不想使用库。我已经更新了你的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循环来确定受影响元素的“深度”。