通过Javascript更改CSS过滤器值

时间:2016-04-09 14:32:40

标签: javascript jquery html css

我正在使用一个非常基本的图像编辑器,但我无法获得范围输入滑块(#fx-slider)来影响实际的css过滤器值。这是代码:

function ChangeFilter() {

  var ifx = document.getElementById("canvasFrame");
  var br = document.getElementById("br");
  var ct = document.getElementById("ct");
  var st = document.getElementById("saturate");

ifx.style.WebkitFilter = "brightness(" + br.value * 10 + "%)");
ifx.style.filter = "brightness(" + br.value * 10 + "%)");

ifx.style.WebkitFilter = "contrast(" + ct.value * 10 + "%)");
ifx.style.filter = "contrast(" + ct.value * 10 + "%)");

ifx.style.WebkitFilter = "saturate(" + st.value * 10 + "%)");
ifx.style.filter = "saturate(" + st.value * 10 + "%)");
}
#canvasFrame {
  width:100px;
  height:50px;
  filter: brightness(100%) contrast(100%) saturate(100%);
  -webkit-filter: brightness(100%) contrast(100%) saturate(100%);
}
<div class="canvasFrame">
  <img src="http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg" alt="image">
</div>
<div class="fx-slider">
  <label for="br">Brightness</label>
  <input id="br" name="br" type="range" min="0" max="200" value="100" onchange="ChangeFilter()">
</div>
<div class="fx-slider">
  <label for="ct">Contrast</label>
  <input id="ct" name="ct" type="range" min="0" max="200" value="100" onchange="ChangeFilter()">
</div>
<div class="fx-slider">
  <label for="st">Saturation</label>
  <input id="st" name="ct" type="range" min="0" max="200" value="100" onchange="ChangeFilter()">
</div>

任何帮助将不胜感激!谢谢。 :)

1 个答案:

答案 0 :(得分:0)

您需要在画布容器中添加一个id,并使用错误的id进行饱和度控制。此外,您应该连接3个控件,否则您只需要设置饱和度。

function ChangeFilter() {
  var ifx = document.getElementById("canvasFrame");  //need to update this id in you html
  var br = document.getElementById("br");
  var ct = document.getElementById("ct");
  var st = document.getElementById("st");  //this id was wrong in your code

  //set all 3 filter values at once.
  ifx.style.webkitFilter = "brightness(" + br.value * 10 + "%) contrast(" + ct.value * 10 + "%) saturate(" + st.value * 10 + "%)";
  ifx.style.filter = "brightness(" + br.value * 10 + "%) contrast(" + ct.value * 10 + "%) saturate(" + st.value * 10 + "%)";
}

CodePen:http://codepen.io/nobrien/pen/BKmevp