如何在显示DIV元素时启动Javascript函数

How to make a Javascript function start when a DIV element is displayed?

本文关键字:启动 Javascript 函数 元素 DIV 显示      更新时间:2023-09-26

我有一个单页的html应用程序。只有一个thml文件有多个div,当点击相关按钮时显示/隐藏。

我在其中一个DIV上使用了一些动画(而不是在"第一页DIV"上)。问题是动画在html文档加载时直接开始,当我带着动画转到那个div时,动画已经结束了。

我的问题是:如何使动画开始只是在那一刻,当它的DIV显示?

下面是代码:
<!DOCTYPE html>
<html>
<head>
<script>
function show(shown, hidden) {
  document.getElementById(shown).style.display='block';
  document.getElementById(hidden).style.display='none';
  return false;
}
</script>
<script>
function myFunction()
{
    var o, qt=[
        ["a","b","c"],
        ["d","e","f"],
        ["g","h","i"]];
    o=document.getElementById("quote1");
    o.innerHTML="";
    for(var i=1;i<4;i++)
        o.innerHTML+="<p id='"quote1_"+i+"'" style='"font-size: 28pt;'">&nbsp;</p>";
    var q=qt[Math.floor(Math.random() * qt.length)];
    document.getElementById("quote1_1").innerHTML=q[0];
    setTimeout(function() { document.getElementById("quote1_2").innerHTML=q[1]; }, 2000);
    setTimeout(function() { document.getElementById("quote1_3").innerHTML=q[2]; }, 3000);
}
window.onload = function(){
   myFunction();
}
</script>
</head>
<body>
<div id="Page1">
<div data-role="page">
<div data-role="content">
<center>
<a href="#" onclick="return show('Page2','Page1');">SHOW ANIMATION</a>
</center>
</div>
</div>
</div>


<div id="Page2" style="display:none">
<div data-role="page" id="main">
<div data-role="content">
<center>
<div id="quote1"></div>
<center>
<a href="#" onclick="myFunction()">Next</a>
</center>
</center>
</div>
</div>
</div>
</body>
</html>

除了Kcent的帖子,还有一个名为"ScrollMagic"的jQuery插件:

http://janpaepke.github.io/ScrollMagic/

它根据滚动速度/页面位置激活动画。你可以在这里找到文档:

http://janpaepke.github.io/ScrollMagic/docs/index.html

使用纯javascript,您可以使用MutationObserver。然而,使用像angularjs或knockoutjs这样的库应该会简单得多。在我看来,MutationObserver是相当复杂的。当MutationObserver还不存在时,一种方法是跟踪对象创建。在dom中创建对象时,可以触发回调。这种方法唯一的大问题是,它不适用于没有显式跟踪的dom更改。MutationObserver将通过用户交互捕获DOM的任何更改。

在您的情况下,一个简单的解决方案是在添加到dom后立即执行。

像这样:

function changeElement(target, source, callback) {
  target.innerHTML = source;
  setTimeout(function() {
    callback(target);
  }, 0);
}
setTimeout(function() {
    changeElement(document.getElementById("quote1_2"), q[1], function (parent) {
       // code here
    }
}, 2000);

您也可以将上面的函数更改为已经包含setTimeout,以使其更清晰。

function changeElement(target, source, callback, wait) {
  setTimeout(function() {
    target.innerHTML = source;
    setTimeout(function() {
      callback(target);
    }, 0);
  }, wait);
}
changeElement(document.getElementById("quote1_2"), q[1], function (parent) {
  // code here
}, 2000);

带0的setTimeout是为了确保在innerHTML更新后执行代码。如果您直接执行回调,则可能在回调中dom尚未可用。


至于动画,你应该看看css3的过渡。https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions动画可以通过缓慢地修改不透明度来完成。这完全取决于你想做什么。


<标题> MutationObserver h1> 是你想做的事情的一种方式。MutationObserver并不那么容易设置。我做了一个小例子:
var target = window.container;
function changeOpacity(target) {
    setTimeout(function(){   
        target.style.opacity = 1;
    }, 100);
}
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
       console.log(mutation);
      if (mutation.type == "childList") {
          for(var i=0; i<mutation.addedNodes.length; i++) {
              changeOpacity(mutation.addedNodes[i]);
          }
      }
  });    
});
// configuration of the observer:
var config = { 
    attributes: true, 
    childList: true, 
    characterData: true
};
// pass in the target node, as well as the observer options
observer.observe(target, config);
setTimeout(function () {
    target.innerHTML = "<div class='elem'>Some text</div>";
}, 2000);

和小提琴:http://jsfiddle.net/8zmc8/

如果你能够使用jQuery,有一个叫做waypoints的库可以处理这个问题:http://imakewebthings.com/jquery-waypoints/

你要找的核心是:
为窗口滚动添加事件监听器
-监听目标div的offsetTop进入视图
-然后触发动画在所需的offsetTop值