javascript style.left返回undefined?

时间:2013-08-05 03:31:19

标签: javascript return undefined

我已将我的css左选择器设置为20%的值,但我得到未定义 ??

我的代码:

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

$(document).ready(function(){

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

});

2 个答案:

答案 0 :(得分:2)

您需要删除错误的value

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

在这种情况下,值为''而不是undefined

如果你不是计算值,你会这样做

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

jQuery

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

如果你想计算百分比,那么你可以这样做

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

  });

答案 1 :(得分:2)

element.style仅包含内联样式或直接应用于该元素的样式。

要获取计算样式,包括从样式表继承的样式,可以使用jQuery的.css()

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

或者,对于原生解决方案,请参阅Why doesn't the DOM style node show styles applied by a style sheet?