有没有一种方法可以用jquery更改类的属性
Is there a way to change the property of a class with jquery?
这个问题可能重复或愚蠢。我读过类似的问题,但不是这个确切的问题。
假设我有两个动态生成的li
,它们的类为.someclass
和.someclass2
,并且都有不同的宽度,需要在页面加载时进行计算。
那么,有没有一种方法可以将计算的宽度设置为类一次,而不是每次生成新的li
时都设置宽度?
我们可以用css来做这件事,如果宽度是已知的,.someclass { width: 20px;} .someclass2 { width: 50px;}
,然后每当一个新元素生成时,css就会应用到它们。
每次发生追加时应用宽度
$('#somediv').click(somefunction);
function somefunction() {
$('#somediv').append('<li class="someclass"><li class="someclass2"></li></li>');
$('.someclass').css('width', $(document).width() - 112); //every time
$('.someclass2').css('width', $(document).width() - 250); //every time
}
应用宽度一次-有办法只应用一次吗?
$('.someclass').css('width', $(document).width() - 112); //once, but it will not work
$('.someclass2').css('width', $(document).width() - 250); //once, but it will not work
$('#somediv').click(somefunction);
function somefunction() {
$('#somediv').append('<li class="someclass"><li class="someclass2"></li></li>');
}
如果有更多的元素,并且这种情况经常发生,会有什么性能差异吗?
这里我们可以使用JS
创建一个cssText
,因此我们可以为每个css
类设置自定义值。
然后创建一个style
元素,并将其内容设置为预定义的cssText
var cssText = '.someClass {width:' + (window.innerWidth - 100) + 'px;} .someClass2 {width:' + (window.innerWidth - 200) + 'px; }',
head = document.head,
style = document.createElement('style');
if (style.styleSheet){
style.styleSheet.cssText = cssText;
} else {
style.appendChild(document.createTextNode(cssText));
}
head.appendChild(style);
现在所有你需要做的:
- 运行上面的代码来创建所需的类
- 随时调用代码,而无需每次添加
css
样式
相关文章:
- 使用jQuery属性滚动到数据
- 删除具有jQuery属性的li
- Jquery 属性代码到 Javascript 属性代码
- 使用 *= 的 jQuery 属性选择器
- 奇怪的jquery属性添加到IE8中的复选框上
- HTML 使用 JavaScript 添加具有 JQuery 属性的元素
- 如何将 fadeOut jQuery 属性与 Javascript 文本片段一起使用
- 不区分大小写的 jQuery 属性选择器
- IE中的jQuery属性选择器
- JQuery属性总是返回相同的值
- 任务不可能:jQuery属性选择器
- 如何在jquery插件EasyDate中使用jquery属性
- onclick的jquery属性监听器
- 动态生成的HTML代码没有jQuery属性
- 如何将多个变量从函数传递到jquery属性
- 当Ajax.BeginForm时在Internet Explorer 8上添加的jQuery属性
- JQuery 属性通配符 包含分隔的空格
- jQuery属性自动切换
- 当jquery属性选中复选框时,Angular ng-model不更新
- 理解使用#的jQuery属性选择器