将内联样式存储到jquery变量中

时间:2012-12-19 00:03:58

标签: javascript jquery

我有以下img标签,

 <img id="image1" src="URL" alt="image1" name="image1" width="137" height="119" border="0" style="position: relative; left: -355px; top: 62px;" >

我想以某种方式,onclick,将以下项目存储到单独的变量中..

  style="position: relative; left: -355px; top: 62px;"

  var left = -355px
  var top = 62px

这可能吗?谢谢!

2 个答案:

答案 0 :(得分:0)

var imageInfo = {style:null, left:null, top:null};

$('#image1').on('click', function() {
  var $this = $(this);
  imageInfo.style = $this.attr('style');
  imageInfo.left = $this.css('left');
  imageInfo.top = $this.css('top');
  console.log('Image Clicked: ', imageInfo);
});

答案 1 :(得分:0)

当然这是可能的,你尝试过这样的事情:

$('#image1').on('click', function () {
    var style = 'style="' + $(this).attr('style') + '"';
    var left = $(this).css('left');
    var top = $(this).css('top');

    alert(style);
    alert(left);
    alert(top);
});

示例:http://jsfiddle.net/9ZXHX/