我希望大家都做得很好。
我试图创建一个灰度按钮,将我整个网站的背景更改为灰色,当我再次单击该按钮时,它将返回到网站的原始颜色。我使用的是JavaScript,HTML和CSS。我尝试在一个按钮中创建两个函数,但也没有成功。
我下面的代码
<button onclick="grayscale()">Grayscale</button>
<style>
body
{
-webkit-filter: grayscale(0);
filter: none;
}
</style>
<script>
function myFunction() {
document.getElementById("myImg").style.filter = "grayscale(100%)";
else function myFunction(){
document.getElementById("myImg").style.filter = "grayscale(0%)";
}
}
</script>
</button>发布于 2022-08-21 17:22:18
<!-- Grayscale button -->
<button onclick="grayscale()">Grayscale</button>
<!-- An image to demonstrate the grayscale effect -->
<hr>
<img src="https://img.freepik.com/free-vector/abstract-colorful-fluid-background_23-2148901720.jpg?w=2000" width="200">
<!-- CSS -->
<style>
/* Remove the following three lines to remove animation */
body {
transition: filter 1s; /* Change "1s" to any time you'd like */
}
body.grayscale {
/* grayscale(1) makes the website grayscale */
-webkit-filter: grayscale(1);
filter: grayscale(1);
}
</style>
<!-- JavaScript -->
<script>
// Grayscale function
function grayscale() {
// Toggling the class "grayscale" on the body
document.body.classList.toggle("grayscale");
}
</script>
发布于 2022-08-21 17:25:03
function grayscale() {
let img = document.getElementById("myImg");
img.classList.toggle("grey");
}.grey {
filter: grayscale(100%);
/* other styles if I want to add them */
}<button onclick="grayscale()">Grayscale</button>
<img src="https://picsum.photos/500" id="myImg" />
更好、更简单的方法是使用
.classList.toogle()(这使您不使用if/ you ),它将自动为您进行检查。此外,您还可以在类选择器中添加更多的样式,并且基本上有更多的控制(例如,使用最小的js添加转换或复杂的关键帧动画)。 https://developer.mozilla.org/en-US/docs/Web/API/Element/classList?retiredLocale=it
发布于 2022-08-21 17:21:18
只需使用一个函数并使用一个if饱和。
function myFunction() {
if(document.getElementById("myImg").style.filter == 'grayscale(100%)')
document.getElementById("myImg").style.filter = "grayscale(0%)";
else document.getElementById("myImg").style.filter = "grayscale(100%)";
}body
{
-webkit-filter: grayscale(0);
filter: none;
} <button onclick="myFunction()">Grayscale</button>
<img id='myImg' src="https://www.fillmurray.com/640/360">
https://stackoverflow.com/questions/73436582
复制相似问题