按ID的滑块不透明度控制元素

时间:2018-04-22 13:14:57

标签: javascript html css

我想使用第二个代码段中的滑块按Element Id更改不透明度 在这种情况下,实现滑块的好方法是什么?

<p id="s1">See effect here</p>
<select onchange="myFunction(this);" size="14">
<option>0 <option>0.1 <option>0.2 <option>0.3 <option>0.4
<option>0.5 <option>0.6 <option>0.7 <option>0.8 <option>0.9
<option selected="selected">1
</select>

<script type="text/javascript">
function myFunction(x) {
 // Return text 'See effect here' of the selected option
 var opacity = x.options[x.selectedIndex].text;
 var el = document.getElementById("s1");
  if (el.style.opacity !== undefined) {
  el.style.opacity = opacity;
  } else { alert("Your browser doesn't support this example!"); } }
</script>

<style type="text/css">
.slidecontainer {width: 100%;}
.slider:hover {opacity: 1;}
</style>
<div class="slidecontainer">
<input type="range" min="0" max="10" value="5">
</div>

2 个答案:

答案 0 :(得分:1)

这个工作正常: Using a slider for the opacity of a div

&#13;
&#13;
// Opacity Slider
$('#bgopacity').on('input', function (value) {
    $('#s1').css({
        opacity: $(this).val() * '.01'
    });
});
&#13;
<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>
<p id="s1">See effect here</p>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

最好是滑块。您将获得滑块值非常容易。这是一个例子

var range = document.getElementById("range");
var imgOne = document.getElementsByClassName("img1")[0];
var imgTwo = document.getElementsByClassName("img2")[0];

range.addEventListener("change", function() {
    imgOne.style.opacity = this.value / this.max;
    imgTwo.style.opacity = (this.max - this.value) / this.max;
});
.img1, .img2 {
  opacity: 0.5;
}
<input id="range" type="range" min="0" max="50" value="25"><br><br>

<img class="img1" height="200" width="200" src="http://www.technocrazed.com/wp-content/uploads/2015/12/beautiful-wallpaper-download-11.jpg" />

<img class="img2" height="200" width="200" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSLg8Fo8YK5SNLqmZUUCjaUh_2Y57jxBgkmjOwxj7dNSui2jZcb" />