//这是html文档的正文。我想让我的按钮改变h1的样式,就像在单击按钮时在黄色和紫色之间切换一样。我尝试使用按钮上的切换功能,但每当我重新加载页面时,按钮都会在过渡中消失。
<body>
<h1>Hello</h1>
<button>Click Me</button>
<button>Click Me</button>
<button>Click Me</button>
<button>Click Me</button>
<button>Click Me</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="index.js" charset="utf-8"></script>
</body>
//this is the js code. the buttons simply disappear when I reload the page
$("button").toggle(function() {
/* Stuff to do every *odd* time the element is clicked */
$("h1").css("color","purple");
}, function() {
/* Stuff to do every *even* time the element is clicked */
$("h1").css("color","yellow");
});发布于 2020-04-30 01:23:09
切换()方法在所选元素的hide()和show()之间切换。所以你要做的就是在加载时有效地隐藏按钮。您需要将您的脚本更改为如下所示。
<script>
let flag=true;
$("button").click(function() {
/* Stuff to do every *odd* time the element is clicked */
flag ? $("h1").css("color","purple"): $("h1").css("color","yellow");
flag=!flag;
});
</script>或者你可以试试toggleClass。定义两个类,紫色和黄色。将节点中的紫色应用为
<h1 class="purple">Hello</h1>然后在脚本中
<script>
$("button").click(function(){
$("h1").toggleClass('yellow');
});
</script>这也是可行的
https://stackoverflow.com/questions/61507542
复制相似问题