gpt4 book ai didi

javascript - 单击按钮后使用 CSS 和 JS 将彩色图像转换为黑白图像

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:54 26 4
gpt4 key购买 nike

我有下面的代码。它仅适用于一个图像/页面。

是否可以使转换图像的功能适用于多个图像(每个图像都有自己的按钮),所有图像都在同一页面上,就像画廊一样?

HTML:

<!DOCTYPE html>  
<html>
<head>
<meta charset="utf-8">
<title>CSS3-Converting Color Image to Black and White Image Using Pure CSS3 Techumber</title>
<meta name="description" content="CSS3-Converting Color Image to Black and White Image Using Pure CSS3">
<meta name="author" content="Aravind Buddha">
<link rel="stylesheet" type="text/css" href="style.css"></link>
</head>
<body>
<div class="container">
<header>
<h1 class="logo">
<a href="http://techumber.com">
<img src="../asserts/img/logostd.png" alt="techumber logo" title="techumber logo" />
</a>
</h1>
</header>
<section class="contant">
<button id="convert">Click here </button>
<img id="img" src="1.jpg" alt="techumber.com CSS3 black and white"/>
</section>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

CSS:

* { 
margin: 0;
padding: 0;
border:0;
}
body {
background: #000;
font-family: helvetica,"Comic Sans MS",arial,sans-serif;
}
.container{
width: 700px;
margin: 0 auto;
}
.logo{
text-align: center;
}
.contant{
margin: 0 auto;
width: 300px;
}
button{
width: 215px;
height: 50px;
margin: 0 0 10px 35px;
font-size: 20px;
font-weight: bolder;
cursor: pointer;
}
.bwImg{
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
-ms-filter: grayscale(100%);
-o-filter: grayscale(100%);
filter: grayscale(100%);
}

JS:

window.onload = function () {  
//get elements
var f = 1,img = document.getElementById('img'),
cvrt = document.getElementById('convert');
//button click event
cvrt.onclick = function () {
if (f) {
img.className = "bwImg";
f = 0;
cvrt.innerHTML = "Convert to Color";
} else {
img.className = "";
f = 1;
cvrt.innerHTML = "Convert to B/W";
}
};
}

我不太了解 JavaScript,所以尽可能明确。

最佳答案

使用filter:grayscale(100%)获取。

$(document).ready(function() {
$('#convert').click(function() {
$('#img').css('filter', 'grayscale(100%)');
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="convert">Click here </button><br>
<img id="img" src="http://lorempixel.com/400/200/" alt="techumber.com CSS3 black and white" />

关于javascript - 单击按钮后使用 CSS 和 JS 将彩色图像转换为黑白图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46306578/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com