简体   繁体   English

使用滑块来实现div的不透明度

[英]Using a slider for opacity of a div

I'm having a bit of trouble having a slider change the opacity value of my div. 我有一个滑块改变我的div的不透明度值有点麻烦。 Here is a fiddle of what I've been working with: https://jsfiddle.net/yfmLk1ad/1/ 这是我一直在使用的小提琴: https//jsfiddle.net/yfmLk1ad/1/

 $('#bgopacity').on('slide', function(value) { $('.background-color').css({ opacity: value * '.01' }); }); 
 .background-color { width: 500px; height: 500px; background: red; opacity: .5; } 
 <div class="background-color"></div> <form> <label>Color Opacity</label> <input type="range" name="bgopacity" id="bgopacity" value="50" min="0" max="100" step="1" onchange="rangevalue.value=value"> <output id="rangevalue">50</output> </form> 

You have to make use of change event. 你必须利用change事件。 And to take the value of the slider like this ($(this).val() , not passing as parameter. This update the rectangle when you finished to choose the value. 并且像这样获取滑块的值($(this).val() ,而不是作为参数传递。这样在完成选择值时更新矩形。

 // Opacity Slider $('#bgopacity').on('change', function (value) { $('.background-color').css({ opacity: $(this).val() * '.01' }); }); 
 .background-color { width: 500px; height: 500px; background: red; opacity: .5; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <label>Color Opacity</label> <input type="range" name="bgopacity" id="bgopacity" value="50" min="0" max="100" step="1" onchange="rangevalue.value=value"> <output id="rangevalue">50</output> </form> <div class="background-color"></div> 


For real time update you can use input event. 对于实时更新,您可以使用input事件。 This is updated when the value is changing. 这个值在更改时会更新。

 // Opacity Slider $('#bgopacity').on('input', function (value) { $('.background-color').css({ opacity: $(this).val() * '.01' }); }); 
 .background-color { width: 500px; height: 500px; background: red; opacity: .5; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <label>Color Opacity</label> <input type="range" name="bgopacity" id="bgopacity" value="50" min="0" max="100" step="1" onchange="rangevalue.value=value"> <output id="rangevalue">50</output> </form> <div class="background-color"></div> 

First, replace 首先,替换

$('#bgopacity').on('slide', function (){...});

with

$('#bgopacity').on('change', function (){..});  

Instead of value use $(this).val() 取而代之的value使用$(this).val()

See it working 看它工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM