JS: event listener for when element becomes visible?

I am building a toolbar that is going to be included into a page. the div it is going to be included in will default to display:none . Is there a way i can put an event listener on my toolbar to listen for when it becomes visible so it can initialize? or will I have to pass it a variable from the containing page?

Thanks


javascript事件处理用户交互,如果你的代码组织得不够,你应该能够在可见性改变的地方调用初始化函数(即你不应该在很多地方改变myElement.style.display,而是调用一个功能/方法,做这个和你可能想要的任何东西)


I had this same problem and created a jQuery plugin to solve it for our site.

https://github.com/shaunbowe/jquery.visibilityChanged

Here is how you would use it based on your example:

$('#contentDiv').visibilityChanged(function(element, visible) {
    alert("do something");
});

There is at least one way, but it's not a very good one. You could just poll the element for changes like this:

var previous_style,
    poll = window.setInterval(function()
{
    var current_style = document.getElementById('target').style.display;
    if (previous_style != current_style) {
        alert('style changed');
        window.clearInterval(poll);
    } else {
        previous_style = current_style;
    }
}, 100);

The DOM standard also specifies mutation events, but I've never had the chance to use them, and I'm not sure how well they're supported. You'd use them like this:

target.addEventListener('DOMAttrModified', function()
{
    if (e.attrName == 'style') {
        alert('style changed');
    }
}, false);

This code is off the top of my head, so I'm not sure if it'd work.

The best and easiest solution would be to have a callback in the function displaying your target.

链接地址: http://www.djcxy.com/p/14610.html

上一篇: 在jQuery中删除事件处理程序的最佳方法是什么?

下一篇: JS:什么时候元素变得可见的事件监听器?