简体   繁体   English

更改不在DOM中的元素的CSS属性

[英]Change CSS properties of an element not in the DOM

I'm trying to add a css property to an element with the following command: 我正在尝试使用以下命令将css属性添加到元素:

$(".pinned").css("left",colPositionLeft);

colPositionLeft is calculated when the page is loaded. colPositionLeft是在加载页面时计算的。

The problem is that the .pinned class is not present in the DOM when the page is loaded, pinned class is add to an element after the user had scroll. 问题在于,加载页面时, .pinned类在DOM中不存在,在用户滚动后将pinned类添加到元素中。 So, the command doesn't work. 因此,该命令不起作用。

How can I set the .pinned css property when the page is loaded but not present in the DOM? 当页面加载但不在DOM中时,如何设置.pinned css属性?

You can dynamically add CSS rules via JavaScript: 您可以通过JavaScript动态添加CSS规则:

document.styleSheets[0].insertRule('.pinned { left: ' + colPositionLeft + 'px; }', 0);

adds the the rule as the first rule. 将规则添加为第一条规则。 To add it as the last rule you can use 要将其添加为最后一条规则,您可以使用

var styleSheet = document.styleSheets[0];
styleSheet.insertRule('.pinned { left: ' + colPositionLeft + 'px; }', styleSheet.cssRules.length);

Both examples add the rule to the first style sheet (included file or <style> tag in the document) which should usually be sufficient. 这两个示例都将规则添加到通常应该足够的第一个样式表(文档中包含的文件或<style>标记)中。 You can of course use other elements in document.styleSheets to add it to another. 您当然可以在document.styleSheets使用其他元素将其添加到另一个元素中。

Note that if you try to do this with a cross-origin style sheet it will throw a SecurityError in at least some browsers. 请注意,如果尝试使用跨域样式表执行此操作,则它将至少在某些浏览器中引发SecurityError

You can use the jQuery on function to modify out for dynamic element that may not have been loaded yet. 您可以使用jQuery on函数修改出可能尚未加载的动态元素。 I often use this function and find it very useful when creating templates and dynamic pages. 我经常使用此功能,并在创建模板和动态页面时发现它非常有用。

$(document).on('scroll', '.pinned', function(){
   $(this).css("left",colPositionLeft);
});

I used this add a reference. 我用这个添加参考。 jQuery scroll jQuery滚动

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

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