0

所以我正在研究一个应该是响应式的 Polymer 元素。为此,我需要访问当前图像的宽度。

这是我的标记

  <div class="meme">
    <div id="memeImage"><img id="memeimg" src="{{img}}"></div>
  </div>

以及(相关的)样式。

  .meme {
    position: relative;
    -webkit-box-align:center;
    -webkit-box-pack:center;
    display:-webkit-box;
  }
  #memeImage {
    z-index: -1;
    border: 0px;
    margin: 0px;
    text-align: center;
    position: relative;
  }

现在我想要的是获得图像的宽度。为此,在我的ready事件中,我添加了这两行:

    console.log(this.$.memeImage);
    console.log(this.$.memeImage.clientWidth);

第一个打印元素就好了,我可以看到clientWidthandoffsetWidth是数字。但第二行打印 0。当我使用 . 时也是如此getComputedStyle()

我认为这可能是因为图像尚未加载,所以我添加了一个事件处理程序:

    this.$.memeImage.addEventListener('onload', function() {
      console.log("image loaded");
    })

但这永远不会受到打击。

我做错了什么,我该如何解决?

4

3 回答 3

2

看起来您的图像的 onload 事件处理程序没有被调用。尝试使用窗口的 onload 事件:

window.onload = function () {
      console.log(document.getElementById('memeimg').clientWidth);
}

window.onload 应该在所有图像加载后(不仅仅是第一个)被触发。无论如何,如果由于某些奇怪的与 Polymer 相关的原因,图像的正常加载事件没有触发,这应该可以解决每个图像的问题:JS:

function onThisImageLoaded(thisImage) {
            console.log(thisImage.clientWidth);
}

然后标记:

<div id="memeImage"><img id="memeimg" src="https://www.gravatar.com/avatar/f9d1450403b864d6b17f30ba0ce0aee3?s=48&d=identicon&r=PG" onload="onThisImageLoaded(this);"></div>
于 2014-05-18T18:09:07.980 回答
2

I believe the most idiomatic polymer solution for this is to use Polymer's event handling.

<div class="meme">
  <div id="memeImage"><img id="memeimg" on-load="{{imageLoaded}}" src="{{img}}"></div>
</div>

Then in your Polymer declaration

Polymer('my-meme', {
  imageLoaded: function() {
    console.log('meme image loaded');
  }
});

This is nice because it doesn't add anything to the top level namespace, it keeps the code related to the meme packaged up together, and it will work even if you show the image only conditionally (e.g. with a <template if="{{something}}">)

You mention in your post that you've tried this:

this.$.memeImage.addEventListener('onload', function() {
  console.log("image loaded");
});

Generally speaking that should work, but there are a couple of typos. Try this (note memeImage -> memeimg and onload -> load):

this.$.memeimg.addEventListener('load', function(loadEvent) {
  console.log("image loaded: ", loadEvent);
})

Also it may be worth experimenting with ready vs domReady though I don't think it should make a difference in this case.

于 2014-05-18T19:06:05.347 回答
0

同意@charlietfl - 你无法获得尚未加载的图像的尺寸 -

事件是'load'和不是'onload'

如果您使用的是 jquery - 试试这个 -

 $("#memeimg").on('load', function () {
        console.log("image loaded");
    }).attr('src', 'http://i.imgur.com/xENQisG.jpg');

关键是在设置源之前附加事件-此处为jsfiddle-如果不可行-从此处检查替代方法

于 2014-05-18T18:08:41.937 回答