问题描述:

I have set my css left selector with value of 20%, but I get undefined??

my code:

http://codepen.io/vincentccw/pen/ouhtk

$(document).ready(function(){

$("#item1").click(function(){

console.log(document.getElementById("item1").style.left.value);

});

});

网友答案:

You need to remove the value that is a error

  $("#item1").click(function(){
    console.log(document.getElementById("item1").style.left);
  });

In this case the value is '' and not undefined

If you wan't the computed value you would do this

  $("#item1").click(function(){
     var element = document.getElementById("item1");
     console.log( window.getComputedStyle( element ).left );
  });

Or with jQuery

  $("#item1").click(function(){
     console.log( $(this).css('left') );
  });

if you want to calculate the percentage then you can do this

  $("#item1").click(function(){
     var parent = $(this).parent().width();
     console.log( 100 * $(this).width() / parent );

  });
网友答案:

element.style only contains inline styles or those applied directly to that element.

To get computed styles, including those inherited from stylesheets, you can use jQuery's .css():

$('#item1').click(function(){
  console.log($(this).css('left'));
});

Or, for a native solution, see Why doesn't the DOM style node show styles applied by a style sheet?.

相关阅读:
Top