简体   繁体   English

如何更改动态创建的元素的 css?

[英]How can I change css for elements created dynamically?

I have a jquery script that generates items dynamically on the scroll.我有一个 jquery 脚本,可以在滚动条上动态生成项目。 By default, the overlay style for these items is set as visibility: hidden I decided to change the overlay style on the fly a checkbox, and make them visible:默认情况下,这些项目的覆盖样式设置为visibility: hidden我决定动态更改覆盖样式复选框,并使它们可见:

 $(' #switch').click(function() {
        if ($(this).prop("checked") == true) {          


            $('.footer-inner').css({ visibility: 'visible' });

        } else if ($(this).prop("checked") == false) {

            $('.footer-inner').css('visibility', 'hidden');

        }
    });

The code trigger well for all the items already created on the page.该代码可以很好地触发页面上已创建的所有项目。 But if I scroll down, the news items don't have the overlay is not visible.但是如果我向下滚动,新闻项目没有覆盖是不可见的。

I would just toggle a CSS class on a parent and use a style to show and hide the element.我只会在父级上切换 CSS 类并使用样式来显示和隐藏元素。 No need to worry about calling the function when the page updates.无需担心页面更新时调用该函数。 It just gets applied.它只是被应用。

 $('#switch').on('change', function() { $(".wrapper").toggleClass("show-footer", this.checked) }).change(); var i = 4; window.setInterval(function() { i++ $(".wrapper").append(`<div>${i}</div><div class="footer-inner">${i}X</div>`) }, 2000)
 .wrapper .footer-inner { display: none; } .wrapper.show-footer .footer-inner { display: block; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" id="switch"><label>Toggle</label> <div class="wrapper"> <div>1</div> <div class="footer-inner">1X</div> <div>2</div> <div class="footer-inner">2X</div> <div>3</div> <div class="footer-inner">3X</div> <div>4</div> <div class="footer-inner">4X</div>

In your way with toggling the visibility, you would need to trigger the function after the page updates.以您的方式切换可见性,您需要在页面更新后触发该功能。 So you would need to call $('#switch').click() when you make the update.所以你需要在更新时调用$('#switch').click()

And depending on the layout, it would be possible to do it in pure CSS using checkbox state.根据布局,可以使用复选框状态在纯 CSS 中完成。

 var i = 4; window.setInterval(function() { i++ $(".wrapper").append(`<div>${i}</div><div class="footer-inner">${i}X</div>`) }, 2000)
 .wrapper .footer-inner { display: none; } #switch:checked + label + .wrapper .footer-inner { display: block; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" id="switch"><label>Toggle</label> <div class="wrapper"> <div>1</div> <div class="footer-inner">1X</div> <div>2</div> <div class="footer-inner">2X</div> <div>3</div> <div class="footer-inner">3X</div> <div>4</div> <div class="footer-inner">4X</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM