求 如何用js给class加上style内样式
求如何用js给class加上style内样式如:<divclass="content"></div>输出效果前台:<divclass="content"style="wi...
求 如何用js给class加上style内样式 如:<div class="content"></div> 输出效果前台:<div class="content" style="width: 1190px;"></div> 万分感谢!
展开
2个回答
展开全部
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>demo</title>
</head>
<body>
<div class="content"></div>
<div class="content"></div>
<div class="content"></div>
<div class="content"></div>
<div class="content"></div>
</body>
<script>
var content = document.getElementsByClassName('content');
for( i = 0; i < content.length; i++ ) {
content.item(i).style.width = '1190px';
}
</script>
</html>
结果:
刚无聊,敲了一个复杂一点的例子,注意 这不是jquery
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>demo</title>
</head>
<body>
<div class="content"></div>
<div class="content"></div>
<div class="content"></div>
<div class="content"></div>
<div class="content"></div>
<div id="content"></div>
<span></span>
<span></span>
<span></span>
</body>
<script>
function $(dom) {
return new test(dom);
}
function test(dom) {
var _this = this;
var prefix = dom.charAt(0);
switch (prefix) {
case ".":
dom = document.getElementsByClassName(dom.slice(1));
break;
case "#":
dom = document.getElementById(dom.slice(1));
;
break;
default:
dom = document.getElementsByTagName(dom);
;
break;
}
_this.domArr = [];
if (dom.constructor == NodeList) {
for (var i = 0; i < dom.length; i++) {
_this.domArr.push(dom.item(i));
}
} else if (dom.constructor == HTMLDivElement) {
_this.domArr.push(dom);
} else {
return false;
}
_this.css = function(name, val) {
var styleObj = {};
if (typeof name == "object") {
for (var i in name) {
styleObj[i] = name[i];
}
} else {
styleObj[name] = val;
}
for (var name in styleObj) {
for (var i = 0; i < _this.domArr.length; i++) {
_this.domArr[i].style[name] = styleObj[name];
}
}
return _this;
};
return _this;
}
$("#content").css("width", "1190px");
$(".content").css("width", "1000px");
$("span").css({
width:"50px",
height:"100px",
display:"block",
"background-color":"#CCC",
"margin-top":"20px"
});
</script>
</html>
结果:
展开全部
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" >
function action1(){
document.getElementById("dv").style.width="200px";
}
function action2(){
document.getElementById("dv").style.width="100px";
}
</script>
</head>
<style>
.a{
width:100px;
height:100px;
background-color:red;
}
</style>
<body>
<div class="a" id="dv">
</div>
<input type="button" onclick="action1();" value="点击增长div宽度" />
<input type="button" onclick="action2();" value="点击还原div宽度" />
</body>
</html>
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |