在html img标签中使用函数的结果

时间:2014-09-10 12:29:35

标签: javascript html function

我尝试使用javascript函数的结果来填充' src' IMG标签的价值。 我想在同一页面的许多地方使用它,否则我想我可以在IMG标签中使用ID并使用getelementbyid更改src。

想法是根据用户屏幕的大小加载图像。

代码没有给我正确的结果:

<html>
<head>
    <script>
        function path_images(image)
        {
            var s = screen.width;
            path = (s<1080) ? "small":"large";
            return path + "/" + image;
        }
    </script>
</head>

<body>
    <h1>Some text</h1>
    <img alt="error" src=path_images("someimage.png")>
    <img alt="error" src=path_images("someotherimage.png")>
</body>

请告诉我怎么做。

3 个答案:

答案 0 :(得分:0)

你可以试试这个。它选择带有标签img的所有元素并更改每个SRC。如果要更改单个图像的来源,则应使用ID或任何其他标识符。

function changeSource() 
{
  aImgs = document.getElementsByTagName("img"); 
  for ( var index in aImgs )
     aImgs[ index ].src = path_images( image_here );
}

答案 1 :(得分:0)

抓住图片:

var images = document.querySelectorAll('img');

将节点列表转换为数组并循环更新src

Array.prototype.slice.call(images).forEach(function (img) {
  img.src = path_images(img.getAttribute('src'));
});

答案 2 :(得分:0)

为了这个目的你需要在body onload上调用一个函数,这个函数会做什么?这个函数将首先获得屏幕宽度,并且在决定是否会有小或大之后它会抓住页面上的所有图像以及它们的src属性,然后在它们的每个(可能是foreach)上循环body onload功能并在路径之前连接小或大,这将满足您的要求。

好的函数无法在img src标记上调用它可以在onclick事件中。在某些事件中调用每个javascript函数。

相关问题