2017-03-04 82 views
0

我有一個內嵌設置不透明度,像這樣的圖像...jQuery的覆蓋不透明度設爲

<img id="theImage" style="opacity: 0.54;" src="...source..." class="gray-scale-img profileImage img-responsive"/> 

我使用IonRangeSlider設置不透明度的新的價值,但問題是,如果我在範圍滑塊上超過0.54,則不透明度將不起作用。它會從0.00調整到0.54,但如果我超過這個,它只會保持在0.54,並且不會變得更亮。

$("#theImage").css({ opacity: opacity }); 

IonRangeSlider

$("#formElement").ionRangeSlider({ 
    min: 0, 
    max: 100, 
    onChange: function(data) { 
    var val = data.from; 
    if (val < 100) { 
     if (val < 10) { 
     var opacity = "0.0" + val; 
     } else { 
     var opacity = "0." + val; 
     } 
    } else { 
     var opacity = "1.0" 
    } 
    $("#theImage").css({ 
     opacity: opacity 
    }); 
    }, 
    onFinish: function() { 
    ... 
    } 
}); 

感謝。

+0

沒有ID到圖像呢? –

+0

爲了清晰起見,我調整了我的代碼 – LargeTuna

回答

0

你正在做太多不必要的計算和分支與opacity變量。它看起來像你試圖把百分比變成小數。只需使用data.from/100作爲不透明度值。

$("#formElement").ionRangeSlider({ 
 
    min: 0, 
 
    from: 54, 
 
    max: 100, 
 
    onChange: function (data) { 
 
    $("#theImage").css('opacity', data.from/100); 
 
    }, 
 
    onFinish: function() { 
 
    // stuff 
 
    } 
 
});
<input id="formElement" type="text" > 
 
<img id="theImage" src="//stackoverflow.com/favicon.ico"> 
 

 
<!-- Resources necessary for the demo to work --> 
 
<link href="http://ionden.com/a/plugins/ion.rangeSlider/static/css/ion.rangeSlider.skinFlat.css" rel="stylesheet"/> 
 
<link href="http://ionden.com/a/plugins/ion.rangeSlider/static/css/ion.rangeSlider.css" rel="stylesheet"/> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://rawgit.com/IonDen/ion.rangeSlider/master/js/ion.rangeSlider.min.js"></script>


編輯:根據文檔,你可以用from屬性來設置默認位置配置滑塊。首先在his answer中使用此概念歸功於zer00ne

2

爲什麼您使用的是if else

確定不透明度直接opacity = val/100

編輯:請參見下面的代碼,你會得到的想法。你也可以看看@gyre的答案,這個答案與IonRangeSlider有類似的實現,所以我會讓這段代碼更一般。

$(function(){ 
 
     var slider = $("#slider"); 
 
     var img = $("#theImage"); 
 
    
 
    slider.change(function(){ 
 
     var opacity = (this.value)/100; 
 
     img.css("opacity",opacity); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
<input id="slider" type="range" id="myRange" value="54"><br> 
 
<img id="theImage" style="opacity: 0.54;" src="https://placehold.it/350x150"> 
 
</div>