对于类作业,我需要根据我点击的相应单选按钮将正方形的图像放置在左侧、右侧或中心位置。
我希望尽可能多地在 JavaScript 中保留样式。但是,这证明是一个问题,因为我无法访问我想要的内容。示例:
这是单选按钮之一:
<input type="radio" id="center" name="position" onclick=moveShape() value="center">center
形状本身:
<span id="square">
</span>
它的 JavaScript:
function moveShape() {
var center = document.getElementById("center");
var shape = document.getElementById("square");
if(center.checked){
// access CSS here
}
然后我想访问样式,例如:
#somenewid {
width: 10px;
height: 10px;
background-color: red;
display: inline-block;
// code to center it
}
我试过设置一个新的 ID。例如 shape.id = "cent";
一次有效,但如果我随后单击另一个单选按钮并返回到中心按钮,它会告诉我 ID 为空。
我没有,也不能得到作业的答案,但我确实需要知道如何设置我的 HTML/JavaScript 元素,以便我能够访问 CSS 样式。
最佳答案
不确定你想使形状相对于什么“居中”,但这应该让你开始:
function moveShape(cb) {
let square = document.getElementById('square');
if (cb.checked) {
square.className = "center";
} else {
square.className = "right";
}
}
#square {
width: 10px;
height: 10px;
background-color: red;
display: inline-block;
position: absolute;
}
.center {
left: 50%;
margin-left: -5px;
}
.right {
right: 0;
margin: auto;
}
.container {
position: relative;
border: 1px solid black;
height: 10px;
}
<label>
<input type="checkbox" onChange="moveShape(this)"> center
</label>
<div class="container">
<span id="square" class="right"></span>
</div>
关于javascript - 选中复选框时使用 JavaScript 访问 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48819145/