使用JavaScript(而不是jQuery)获取图像的替代文本和源属性

Get alternative text and source attributes of an image using JavaScript (not jQuery)

本文关键字:文本 属性 图像 获取 JavaScript jQuery 使用      更新时间:2023-09-26

我有以下标记:

<h1 id="logoImage">
    <a href="/">
        <img src="http://path-to-image.jpg" alt="Title of site" />
    </a>
</h1>

我想获得"src"answers"alt"的值,并以一种稍微不同的方式使用它们,同时从页面中删除图像元素。

<h1 id="logoImage">
    <a href="/" style="background-image: url('http://path-to-image.jpg')">
        Title of Site
    </a>
</h1>

我不太熟悉普通的JavaScript,所以,这让我很困惑。

你对如何解决这个问题有什么想法吗?

window.addEventListener('load', function load(){
    var logo = document.getElementById('logoImage'),
        img,
        parent;
    if (!logo) {
        return;
    }
    img = logo.querySelector('img');
    if (!img) {
        return;
    }
    parent = img.parentNode;
    parent.style.backgroundImage = 'url(' + img.src + ')';
    parent.style.display = 'block';
    parent.style.width = img.width + 'px';
    parent.style.height = img.height + 'px';
    parent.textContent = img.alt;
});

http://jsfiddle.net/q7brkkbt/1