简体   繁体   中英

How can I add inline css using jquery data attribute with css3 prefix

This Code is good Working for background size inline css ex:

style="background-size:cover"

$(".tp-sliderSection .item").css('background-size', function(){
  $(this).css('background-size',$(this).data("bg-size"));
});

<div data-bg-size="cover"></div>

But I need to use it

$(".tp-sliderSection .item").css('background-size', function(){
  $(this).css('background-size',$(this).data("bg-size"));
  $(this).css('-webkit-background-size',$(this).data("bg-size"));
  $(this).css('-moz-background-size',$(this).data("bg-size"));
});

Output css style I need

  style="background-size:cover; -webkit-background-size:cover; -moz-background-size:cover"

ETC

Your original code should have been working fine, but in case it didn't, you can try .attr() . I had often seen that sometimes there's a problem with .data() but .attr() seems to be the fix.

Also read: http://api.jquery.com/css/ :

As of jQuery 1.8, the .css() setter will automatically take care of prefixing the property name. For example, take .css( "user-select", "none" ) in Chrome/Safari will set it as -webkit-user-select, Firefox will use -moz-user-select, and IE10 will use -ms-user-select.

Also one thing that is going wrong is returning. You just need to return the bg-size whereas you are setting it there. You had already made the function of background-size and now you just need to return the color. Have a look here: http://jsbin.com/xurevijunu/edit?html,css,js,console,output

As of jQuery 1.4, .css() allows us to pass a function as the property value:

$( "div.example" ).css( "width", function( index ) { return index * 50; });

This example sets the widths of the matched elements to incrementally larger values.

Note : If nothing is returned in the setter function (ie. function( index, style ){} ) , or if undefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.

So, you can try:

$(".tp-sliderSection .item").css('background-size', function(){
  return $(this).attr("data-bg-size");
});

Try something like this. You can bracket the css with this syntax...

$(".tp-sliderSection .item").css('background-size', function(){
  $(this).css({ 'background-size’ : $(this).data('bg-size’),‘-webkit-background-size' : $(this).data('bg-size’), '-moz-background-size’ : $(this).data('bg-size')  });
 });

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