Javascript:无法在 div 单击时更改背景或更改元素上的边距左



我试图在这个简单的例子中测试更改backgroundColormarginLeft:https://jsfiddle.net/ntqLo6v0/2/

无法使其发挥作用。

var collapsed = 0;
$('[data-toggle=collapse-button]').click(function() {
if (collapsed == 0) {
close();
} else {
open();
}
});
function close() {
document.getElementById("button").style.backgroundColor = "blue";
(document.getElementsByClassName("content")[0]).style.marginLeft = "20px";
collapsed = 1;
}
function open() {
document.getElementById("button").style.backgroundColor = "red";
(document.getElementsByClassName("content")[0]).style.marginLeft = "120px";
collapsed = 0;
}
.content {
background-color: green;
width: 200px;
height: 100px;
}
#button {
background-color: red;
width: 100px;
height: 50px;
margin: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button" data-toggle="collapse-button">
button
</div>
<div class="content">
some content here
</div>

只有一个小问题:$('[data-toggle=collapse-button]')

您正在使用jQuery,但没有定义它。这就是为什么您在控制台中获得Uncaught ReferenceError: $ is not defined

这是您更新的fiddle,我在其中添加了jQuery(在左侧资源中(,以便使您的示例运行。

最新更新