[英]Only fire one onmouseover when hovering over multiple elements
I'd like to have basic code like the following: 我想要以下基本代码:
<span onmouseover="alert('hi')">Hello, <span onmouseover="alert('hello')">this</span> is a test</span>
However, I'd like to keep it from firing both of these events if both are being hovered over; 但是,如果两个事件都悬停在上面,我希望它不会触发这两个事件。 eg if I hover over "this" it should fire only its event and alert "hello."
例如,如果我将鼠标悬停在“ this”上,它将仅触发其事件并提醒“ hello”。 How can I do this?
我怎样才能做到这一点?
Thank you in advance! 先感谢您!
$(".container").hover(function(){ alert($(this).attr("id")); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="container" id="hi"> Hello, </span> <span class="container" id="hello"> this </span> <span class="container" id="hi"> is a test </span>
I am going to assume that the overlapping elements are not the same size. 我将假设重叠元素的大小不相同。 Ie one is bigger than the other.
即一个大于另一个。
HTML and inline js: HTML和内联js:
<span class="container" id="hi">
Hello,
</span>
<span class="container " id="hello">
this </span>
<script>
var hello =
document.getElementById("hello");
var this =
document.getElementById
("this");
hello.addEventListener("click
",pop("hello"));
this.addEventListener("click",pop(" hi");
function pop(string) {
window.alert(string);
}
<\script>
That being said very little is mentioned about the nature of the elements this and hello. 话虽如此,却很少提及this和hello元素的性质。 Op plz show your CSS and update ques
Op plz显示您的CSS并更新问题
Here's the relevant portion of what I ended up using. 这是我最终使用的相关部分。 I used JQuery.
我使用了JQuery。
var mouseHovered = function(element) {
//get all hovered spans
var hoveredElements = $("span:hover");
//get the element with the smallest text
var smallestElement;
for(var i=0; i<hoveredElements.length; i++) if(!smallestElement || hoveredElements[i].textContent.length < smallestElement.textContent.length) smallestElement = hoveredElements[i];
//if this is the smallest text in the elements
if(element == smallestElement) {
//log the text
console.log(element.textContent);
}
}
You need to prevent Event bubbling
when you hover/click
on inner span. hover/click
内部跨度时,需要防止Event bubbling
。 This can be done using event.stopPropagation() . 这可以使用event.stopPropagation()完成 。
Look at two solutions provided at this JSFiddle . 查看此JSFiddle提供的两个解决方案。
Solution 1 - Use of e.stopPropagation()
in the handler function innerSpan()
. 解决方案1 -使用
e.stopPropagation()
的处理函数innerSpan()
Solution 2 - Use of event.stopPropagation()
in inline onclick
event. 解决方案2-在嵌入式
onclick
事件中使用event.stopPropagation()
。
<span onclick="alert('Outer span');">
Outer
<span onclick="event.stopPropagation(); alert('Inner span');">
Inner
</span>
</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.