我正在尝试使用 javascript
来切换 div
的大小。为了了解如何执行此操作的基本思想,我尝试复制此示例:Toggling Div (JSFiddle)
但由于某种原因它不起作用,尽管我已经从工作的 JSFiddle 复制了它。这是为什么?这是我的复制品:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<style type="text/css">#topbar {
background: orange;
color: white;
height: 10px;
text-align:center;
}</style>
<script type="text/javascript">
$("#topbar").click((function() {
var i = 0;
return function() {
$(this).animate({
height: (++i % 2) ? 40 : 10
}, 200);
}
})());
</script>
</head>
<body>
<div id='topbar'>toggle me</div>
</body>
</html>
最佳答案
哇!您根本没有添加 jQuery!将其添加到您的<head>
中在调用脚本之前。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
您一定在控制台中遇到了此错误:
Reference Error: $ not defined.
<小时/>
您正在使用this
不在上下文中。当你把它放在一个函数中时,它就会搞砸。这样做:
$(function () {
$("#topbar").click(function () {
var i = 0;
$(this).animate({
height: (++i % 2) ? 40 : 10
}, 200);
return false;
});
});
this
您使用的,将以您的内部功能作为其上下文。自从你的<div>
在 <script>
之后,请将其包含在$(function () {})
内.
关于javascript - 通过 javascript 切换 div 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41203614/