[英]Make hover affect child element
I have a couple of elements on my page with the following structure: 我的页面上有几个具有以下结构的元素:
<div class="selector-wrapper">
<div class="selector"></div>
</div>
I now want the .selector
elements to change to the hover state, when the user hovers the parent element. 现在,当用户将父元素悬停时,我希望
.selector
元素更改为悬停状态。
I've found this code (I just added $(this)
), but it gives me an error: 我找到了这段代码(我刚刚添加了
$(this)
),但是它给了我一个错误:
[Error] RangeError: Maximum call stack size exceeded.
[错误] RangeError:超出最大调用堆栈大小。
$('.selector-wrapper').on('mouseenter mouseleave', function(e) {
$(this).find('.selector').trigger(e.type);
})
What's wrong with this code? 此代码有什么问题?
The issue is because the event you fire on the child element is then bubbled up the DOM back to the .selector-wrapper
which then fires on the child again and so on recursively. 问题是因为您在子元素上触发的事件随后会在DOM上冒泡返回到
.selector-wrapper
,然后再次在子元素上触发,以此类推。
Instead, don't fire the event on the child element, but do whatever logic you require in the event handler, such as adding a class to change the styling. 相反,不要在子元素上触发事件,而是执行事件处理程序中需要的任何逻辑,例如添加一个类来更改样式。 Try this:
尝试这个:
$('.selector-wrapper').on('mouseenter mouseleave', function(e) { $(this).find('.selector').toggleClass('foo'); // whatever logic you require here... });
.selector-wrapper { width: 100%; height: 100px; background-color: #C00; } .selector { width: 50px; height: 50px; background-color: #0C0; } .foo { width: 100px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="selector-wrapper"> <div class="selector"></div> </div>
Use CSS: 使用CSS:
.selector-wrapper:hover .selector{
/* Css code goes here..*/
}
It's also easy with css: 使用CSS也很容易:
.selector-wrapper:hover .selector {
/* Your code*/
}
If you use jQuery, you can easyly use this function: 如果您使用jQuery,则可以轻松使用此功能:
$('.selector-wrapper').hover(function() {
// Your code
}
Example: 例:
$(document).ready(function() { $('.selector-wrapper').hover(function() { $('.selector').toggleClass('show'); }); });
.selector-wrapper { height: 100px; width: 100px; background-color: grey; } .selector { color: white; text-shadow: 5px white; display: none; z-index: 2; font-size: 14px; text-align: center; } .show { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="selector-wrapper"> <div class="selector">JQuery</div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.