【问题标题】:How to apply this method to all future matching elements as well?如何将此方法应用于所有未来的匹配元素?
【发布时间】:2013-05-09 18:22:08
【问题描述】:

以下 javascript/jquery sn-p 将 css 应用于 DOM 中所有当前匹配的元素。

$('.centeredByJquery').each(function(){
    $(this).css({'margin-left': -parseInt($(this).css('width'))/2,
                'left':'50%',
                'margin-top': -parseInt($(this).css('height'))/2,
                'top':'50%'});
})

如何将此方法也应用于所有未来的匹配元素?

【问题讨论】:

  • 你打算用centeredByJquery类添加更多元素吗?
  • 您不能设置尚不存在的元素的样式属性,它只是不能委托给父元素的东西,您必须将样式标签插入head 代替,或者想办法用常规 CSS 做同样的事情。
  • 添加新元素时只需添加类centeredByJquery
  • @tymeJV: 是的,当由 ajax 更新时
  • 答案是“当你更新DOM时,你调用了运行这段代码的方法!”

标签: javascript jquery


【解决方案1】:

你不能......唯一的方法是使用间隔:

setInterval(function(){
    $('.centeredByJquery').each(function(){
        $(this).css({'margin-left': -parseInt($(this).css('width'))/2,
                    'left':'50%',
                    'margin-top': -parseInt($(this).css('height'))/2,
                    'top':'50%'});
    })
},1000);

但这是一个糟糕的主意..

如果您知道何时插入新元素,则只需调用一个函数即可将该元素居中。

【讨论】:

    猜你喜欢
    • 2013-05-19
    • 2014-12-08
    • 2021-10-14
    • 2021-01-04
    • 1970-01-01
    • 2020-05-24
    • 2011-05-27
    • 1970-01-01
    • 2011-10-17
    相关资源
    最近更新 更多