1

有没有办法让 jQuery(或任何 javascript)更改 CSS 方案,而不仅仅是将样式应用于与描述符匹配的当前元素?

假设我的 css 上有这个.bla{ width: 200px;}。如果我运行,$('.bla').css('width', 300);那么 jQuery 只会将其应用于现有元素。

我想要的是一种使新宽度成为新 .bla 元素的规则的方法。为了做到这一点,如果我继续添加 .bla 元素,那么它们将是 300 宽。

有没有办法做到这一点?

4

3 回答 3

2

试试这个:

var style = $('<style>body { background: green; }</style>')
$('html > head').append(style);

这是取自链接

于 2012-12-29T22:30:17.643 回答
0

当你运行$('.bla').css('width', 300);它是由于你的页面中的一个条件。

如果将此条件存储在变量中,那么每次添加新的匹配元素时,您都可以检查它们是否需要修改

var someCondition=false;

/* later in code*/
$('.bla').css('width', 300);
someCondition=true;

/* then when add elements*/

var newBla=$('<div class="bla">')
if( someConditon){
  newBla.css('width', 300);
}

如果您使用 CSS 和应用类来执行此操作,则可以使用:

toggleClass( 'bla_300_class', someCondition); /* second arument is boolean to add or remove*/
于 2012-12-29T22:34:04.273 回答
0

你可以这样做:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/jquery-ui.min.js"></script>
</head>
<body>
<div class="style">
<style>.bla{ width: 200px;}</style>
</div>
<div id="divs"></div>

</div>
<button id="adddiv">Add div</button>
<button id="changeWidth">Click To Change Width</button>
<script>
$(function(){
$("#adddiv").click(function(){
$("#divs").append('<div class="bla" style="border:1px solid red;height:20px;margin:2px;">');
});
$("#changeWidth").click(function(){
$(".style").html("<style>.bla{width:300px;}</style>")
});
});
</script>
</html>

你可以在这里在线测试脚本JsFiddle

于 2012-12-29T22:39:45.917 回答