我需要使用这个JS,但需要使用类和ID。这可能吗?
document.getElementsById('container').style.marginLeft = '350px';
我试过了,但它没有用
document.getElementsByClassName('container').style.marginLeft = '350px';
答案 0 :(得分:1)
getElementsByClassName
返回一个集合/数组。所以你只需要附加索引号。
document.getElementsByClassName("whatever")[0]
获得第一个。
答案 1 :(得分:1)
document.querySelector('.container').style.marginLeft = '350px';

<div class="container" style="background: #000; width: 50px; height: 50px;"></div>
&#13;
答案 2 :(得分:-1)
这很有用。
document.getElementsByClassName('container')[0].style.marginLeft = '350px';
我认为这对我的具体情况更好:
function openNav() {
document.getElementById('side').style.width = '350px';
document.querySelector('.container').style.marginLeft = '350px';
}
.sidenav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
}
.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
transition: 0.3s;
}
.sidenav a:hover {
color: #f1f1f1;
}
.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
}
.container {
transition: margin-left .5s;
padding: 16px;
}
<!DOCTYPE html>
<html>
<body>
<div id="side" class="sidenav">
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
<div class="container">
<span style="font-size:30px;cursor:pointer" onclick="openNav()">☰</span>
</div>
</body>
</html>