javascript - 将样式属性应用于后续元素的正确方法

标签 javascript jquery

如何通过jQuery/javascript给后面的元素添加css属性?

这是我的尝试:但失败了:

// failed
$('.yah').load(function() {
  $(this).css({ border: "2px solid red" });
});

// failed
$('.yah').ready(function() {
  $(this).css({ border: "2px solid red" });
})

setTimeout(function() {
  $('body').append("<div class='yah''>123</div>");
}, 2000);

最佳答案

您可以使用 MutationObserver 并观察 childList 中的变化,当添加特定节点时您可以更改其 css。

var body = document.querySelector('body')

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type == 'childList') {
      mutation.addedNodes.forEach(function(node) {
        node = $(node);
        if (node.hasClass('yah')) node.css({
          'border': '1px solid red'
        })
      })
    }
  });
});

observer.observe(body, {
  childList: true
})

setTimeout(function() {
  body.innerHTML += "<div class='lorem'>123</div>"
}, 1000);

setTimeout(function() {
  body.innerHTML += "<div class='yah'>123</div>"
}, 2000);

setTimeout(function() {
  body.innerHTML += "<div class='ipsum'>123</div>"
}, 2500);

setTimeout(function() {
  body.innerHTML += "<div class='yah'>123</div>"
}, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 将样式属性应用于后续元素的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47072565/

相关文章:

javascript - 如何绑定(bind)到 jquery-mobile pagebeforeload 事件?

javascript - 是否可以并允许将自定义(自己的)PayPal 按钮与 Express Checkout 和 REST API 一起使用?

javascript - Google Analytics 在哈希变化时设置页面 View

javascript - 我无法访问对象内数组中的所有元素

javascript - 运行 jQuery,重新加载,冲洗并重复......如何?

javascript - 在 Javascript 中解析 JSON

javascript - easeljs - 容器 mouseEnabled 不起作用

JQuery 淡出操作

javascript - 下拉菜单栏

javascript - 如果 JavaScript 的 hide 函数中的 div 为空,则隐藏 h1 标签