简体   繁体   中英

Incrementing CSS value by a percent with jQuery

I'm trying to increment a % value of a CSS element with jQuery as is outlined in the answer with 104 upvotes here ( Increment css top property using jquery ).

I've created this fiddle ( https://jsfiddle.net/twLxa3o7/ ) to play with. It's supposed to increment the brightness of the image down 10% each time you click the button, but it's not working. The primary line of code is $("#image-" + image_id + "").css("-webkit-filter", "brightness(-=10%)"); .

Any ideas?

I've updated your fiddle to make it work: https://jsfiddle.net/1q3mtm1e/

The initial brightness is declared in the code, and whenever you click the button the function gets the image ID from the data-image-id attribute on the button. It will then subtract 10% from the initial brightness and apply the new brightness.

var brightness = 50;

function darkenImage(imageId, brightness) {
    $("#image-" + imageId + "").css("-webkit-filter", "brightness(" + brightness + "%");
}

$(".button-class-here").on( "click", function() {
    var imageId = $(this).data("image-id");
    brightness -= 10;
    darkenImage(imageId, brightness);
});

You can create a variable which stores the value to be set as a Number , increment variable by 10 , concatenate "%"

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> var n = 0; function darken_image(image_id) { $("#image-" + image_id + "") .css("-webkit-filter", "brightness(" + (n += 10) + "%)"); console.log("n:", n) return false; } </script> <button type="button" onclick="darken_image(23)">+</button> <span id="image-23" style="border: 1px red dashed; display: block; position: relative; clear: both; -webkit-filter: brightness(100%);"> <img src="https://assets.servedby-buysellads.com/p/manage/asset/id/29712"> </span> 

jsfiddle https://jsfiddle.net/twLxa3o7/2/

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