例如
<div class="test"></div>
<script>
let element=document.querySelector("test")
//单独修改,注意ccs中间的杠去掉,改成驼峰命名:
element.style.borderLeft="1px solid red"
element.style.borderRight="1px solid red"
//或者使用 .style.cssText 属性同时修改:
elment.style.cssText="border-left:1px solid redborder-right:1px solid red"
</script>
<!DOCTYPE html><html>
<head>
<title>测试页面2</title>
<meta charset="UTF-8"/>
<style>
.tdiv{
border:2px solid
}
</style>
<script>
function test(ele){
var pDiv=ele.parentNode
if(pDiv.className==" "){
pDiv.className="tdiv"
}else{
pDiv.className=" "
}
}
//还可以用classList,这种方法更流畅
function test2(ele){
var pDiv=ele.parentNode
if(pDiv.classList.contains("tdiv")){
pDiv.classList.remove("tdiv")
}else{
pDiv.classList.add("tdiv")
}
}
</script>
</head>
<body>
<div>
<a onclick="test(this)">测试</a>
</div>
</body>
</html>
<!doctype html><html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<div id="container" style="width: 480px height: 220pxborder:1px solid #e3e3e3" onclick="renderLink()">
<a href="#" class="mya">Test1</a>
<a href="#">Test2</a>
<a href="#" class="mya">Test3</a>
<a href="#" class="mya">Test4</a>
<a href="#" class="mya">Test5</a>
<a href="#">Test6</a>
</div>
</body>
</html>
<script type="text/javascript">
function renderLink(){
var alist = document.getElementsByClassName("mya")
if(alist){
for(var idx = 0 idx < alist.length idx ++){
var mya = alist[idx]
mya.style.color = "red"
mya.style.fontSize = "36px"
}
}
}
</script>
先用document.getElementsByClassName("className")取得所有class为className的元素,再循环添加样式即可,如果用JQuery会简单很多;也可以自己用JS封装一个函数实现JQuery一样的效果
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)