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

时间:2017-09-19 17:32:41

标签: javascript html css

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

是否有可能将图像转换为多个图像(每个图像都有自己的按钮),所有这些图像都在同一个页面上,如图库?

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,所以要尽可能明确。

1 个答案:

答案 0 :(得分:1)

使用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" />