change image opacity using javascript

后端 未结 7 1813
失恋的感觉
失恋的感觉 2020-12-05 04:11

how can I change image opacity using javascript? I\'m going to create a fading effect using javascript, is there any sample? is there anything like image.opacity that can be

相关标签:
7条回答
  • 2020-12-05 04:44

    In fact, you need to use CSS.

    document.getElementById("myDivId").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");
    

    It works on FireFox, Chrome and IE.

    0 讨论(0)
  • 2020-12-05 04:48

    First set the opacity explicitly in your HTML thus:

    <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px; opacity:1"></div>
    

    otherwise it is 0 or null

    this is then in my .js file

    document.getElementById("fadeButton90").addEventListener("click", function(){
    document.getElementById("box").style.opacity  =   document.getElementById("box").style.opacity*0.90; });
    
    0 讨论(0)
  • 2020-12-05 04:50

    You can use CSS to set the opacity, and than use javascript to apply the styles to a certain element in the DOM.

    .opClass {
        opacity:0.4;
        filter:alpha(opacity=40); /* For IE8 and earlier */
    }
    

    Than use (for example) jQuery to change the style:

    $('#element_id').addClass('opClass');
    

    Or with plain javascript, like this:

    document.getElementById("element_id").className = "opClass";
    
    0 讨论(0)
  • 2020-12-05 04:52

    You could use Jquery indeed or plain good old javascript:

    var opacityPercent=30;
    document.getElementById("id").style.cssText="opacity:0."+opacityPercent+"; filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity="+opacityPercent+");";
    

    You put this in a function that you call on a setTimeout until the desired opacity is reached

    0 讨论(0)
  • 2020-12-05 05:03

    Supposing you're using plain JS (see other answers for jQuery), to change an element's opacity, write:

    var element = document.getElementById('id');
    element.style.opacity = "0.9";
    element.style.filter  = 'alpha(opacity=90)'; // IE fallback
    
    0 讨论(0)
  • 2020-12-05 05:08

    You could use jQuery's animate or fadeTo.

    0 讨论(0)
提交回复
热议问题