简体   繁体   中英

How to use CSS filters in JavaScript?

I would like to use CSS filters in JavaScript.

Example of CSS filters:

.filter {
    -webkit-filter: blur(20px); /* Blur filter */
    -webkit-filter: invert(1); /* Invert filter */
    -webkit-filter: hue-rotate(100deg); /* Rotate Hue */
    ...
}

For example, how can I make a blurred image using JavaScript?

<img id="image" onmouseover="ImageHover();" src="source.png"/>

while

function ImageHover() {
    document.getElementById('image').??????='???'
}

I hope you guys understand what I want.

I recommend using this so the function can be used with any element/Img you want later

<img id="image" onmouseover="ImageHover(this);" src="source.png"/>

function ImageHover(el){
    el.classList.add("filter");
};

You need to give use to that element's property, as such:

var image = document.getElementById('image');
image.style.webkitFilter = "blur(20px);";

or

image.style["-webkit-filter"] = "blur(20px);";
var photo = document.getElementById('yourId');

function sepia(){
    photo.style.filter = "sepia(100%)";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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