我想返回一个包含CSS规则所有内容的字符串,就像您在内联样式中看到的格式一样.我希望能够在不知道特定规则中包含的内容的情况下执行此操作,因此我不能仅通过样式名称将其拉出(如.style.width等)
CSS:
.test {
width:80px;
height:50px;
background-color:#808080;
}
Run Code Online (Sandbox Code Playgroud)
到目前为止的代码:
function getStyle(className) {
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
for(var x=0;x<classes.length;x++) {
if(classes[x].selectorText==className) {
//this is where I can collect the style information, but how?
}
}
}
getStyle('.test')
Run Code Online (Sandbox Code Playgroud) 假设规则如下:
.largeField {
width: 65%;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法以某种方式获得'65%',而不是像素值?
谢谢.
编辑:不幸的是,在我的情况下使用DOM方法是不可靠的,因为我有一个导入其他样式表的样式表,因此cssRules参数以null或未定义的值结束.
但是,这种方法适用于大多数简单的情况(一个样式表,文档头标记内的多个单独的样式表声明).
我有一个div,我想知道是否有办法使用jQuery获得百分比的宽度.
这是我的代码:
$(document).ready(function(){
var f = $('.f').width();
alert(f);
});
Run Code Online (Sandbox Code Playgroud)
我尝试使用%这样的参数width(%),但这是将宽度设置为%不以百分比格式获取值.有人可以告诉我,我应该怎样做才能获得百分比?
任何帮助都非常感谢.
我想以百分比形式获得元素的宽度.我使用以下函数来获取样式,但它以像素为单位给出值.这里变量样式可以是任何css属性,如宽度,高度等.
this.getStyle = function(style) {
var elementStyle = window.getComputedStyle(that.element);
var value = elementName.getPropertyValue(style);
return value;
}
Run Code Online (Sandbox Code Playgroud) 如果我alert其中有一个CSS选择器设置为元素width:100%,我得到它在px,是有一些方法来得到它%从CSS设置,我需要它来修复一些脚本流体布局.
// css
.my-element {
width:100%;
}
// javascript
alert('width: '+$('.my-element').css('width'));
// this alerts "width: 1116px" instead of "width: 100%"
Run Code Online (Sandbox Code Playgroud)
也许这样的事情总是如此?
alert($('.my-element').outerWidth() == $('.my-element').parent().outerWidth());
Run Code Online (Sandbox Code Playgroud)