简体   繁体   English

使用Java插入CSS规则

[英]Inserting a CSS Rule with Javascript

I'm having trouble inserting a new CSS rule with Javascript in order to adjust the width of a display block with a fixed position to the width of the window. 我无法在Java脚本中插入新的CSS规则,以便将固定位置的显示块的宽度调整为窗口的宽度。 Could someone explain why this isn't working? 有人可以解释为什么这行不通吗? Here's the jsfiddle for the HTML, CSS, and Javascript (along with a bit of jQuery) involved: http://jsfiddle.net/b9knL/ and this is the Javascript in question: 这是涉及HTML,CSS和Javascript(以及一些jQuery)的jsfiddle: http : //jsfiddle.net/b9knL/ ,这是有问题的Javascript:

$(function () {
                function change_header(){ 
                     var sheets = document.styleSheets;
                     var sheet = document.styleSheets[0];
                     var mywidth = $(window).width();
                     var selector = "header{ width: "+mywidth+"; }";
                     sheet.insertRule(selector, index);
                }
                change_header();

                $(window).resize(function() {
                        change_header();
                });
});

Since it is position:fixed just add width:100% to the css rule and it will auto adjust on its own.. 由于它是position:fixed只需将css规则添加width:100% ,它将自行调整。

header{
    background-color: #005e00;
    display: block;
    position: fixed;
    z-index: 500;
    width:100%;
    box-shadow: 0px 5px 5px #888888;
}

no need for scripting.. 不需要脚本。

Demo at http://jsfiddle.net/b9knL/2/ 演示位于http://jsfiddle.net/b9knL/2/

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

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