如何使用 javascript 更改网站图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6846835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:04:36  来源:igfitidea点击:

How to change a website image with javascript?

javascriptgreasemonkey

提问by Stian Olsen

I'm working with my first Greasemonkey script.

我正在使用我的第一个 Greasemonkey 脚本。

And its for a website that have a logo, i want to change the image to a image i have created, and i wonder how i do this?

对于带有徽标的网站,我想将图像更改为我创建的图像,我想知道我是如何做到这一点的?

like use JavaScript to edit the current html document and replace the image.

比如使用 JavaScript 来编辑当前的 html 文档并替换图像。

Thanks for any help!

谢谢你的帮助!

Edit:The image is inside a <img>tag, the image i want to change/replace is in this code:

编辑:图像在<img>标签内,我要更改/替换的图像在此代码中:

<img class="fb_logo img" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo" width="170" height="36">

Here is the javascript code i tryed and didnt work:

这是我尝试过但没有用的 javascript 代码:

var myImage = document.querySelector('.fb_logo img');
myImage.src = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";

回答by zzzzBov

Knowing that you can use browser-specific javascript is a plus.

知道您可以使用特定于浏览器的 javascript 是一个加分项。

Use querySelectorAll.

使用querySelectorAll.

var img = document.querySelectorAll('.yourClass')[0];

Note: you're possibly selecting more than one element, so it's returning a nodelist rather than a single node, remember to select the first item in the list.

注意:您可能选择了多个元素,因此它返回一个节点列表而不是单个节点,请记住选择列表中的第一项。

Better yet, use querySelector

更好的是,使用 querySelector

var img = document.querySelector('.yourClass');

回答by cwallenpoole

var logos = document.getElementsByClassName("fb_logo");

for( var i = 0; i < logos.length; i++ )
{
    // true for all img tags with the fb_logo class name
    if( logos[ i ].tagName == "IMG" )
    {
        logos[ i ].src = "http://www.computerweekly.com/blogs/it-downtime-blog/lolcat-tan.jpg"
    }
}

回答by Brock Adams

Okay, here's a complete Greasemonkey script that swaps the logo image at Facebook under real-world conditions (meaning that the image may be in different places and you have to deal with the container and background images, etc.).

好的,这是一个完整的 Greasemonkey 脚本,它在现实世界的条件下交换 Facebook 上的徽标图像(意味着图像可能位于不同的地方,您必须处理容器和背景图像等)。

Note that this script looks for the image in two types of locations, and deals with the surrounding HTML, and CSS, if necessary.

请注意,此脚本在两种类型的位置查找图像,并在必要时处理周围的 HTML 和 CSS。

Also note that it uses jQuery -- which is a godsend for writing GM scripts.
Finally: note that I avoid Facebook, and only know of the one logo location (plus the one that the OP reports. If there are new/different locations, deal with them in a similar manner.

还要注意,它使用了 jQuery——这是编写 GM 脚本的天赐之物。
最后:请注意,我避免使用 Facebook,并且只知道一个徽标位置(加上 OP 报告的那个位置。如果有新的/不同的位置,请以类似的方式处理它们。

// ==UserScript==
// @name            _Facebook Logo Swap
// @include         http://www.facebook.com/*
// @include         https://www.facebook.com/*
// @require         http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==

/*--- Found FB logo at:
    "h1#pageLogo a" as a backgound image.

    It's reportedly also at: "img.fb_logo.img"
*/
var desiredImage    = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";

//--- Straight image swap:
$('img.fb_logo').attr ('src', desiredImage);


/*--- Replace the link's -- with the logo as a background -- contents with just a plain image.
    Since this image is transparent, clear the old BG image.
    Also constrain the new img to its container.
*/
$('#pageLogo a').css ('background-image', 'none')
                .append ('<img>').find ('img')  .attr ('src', desiredImage)
                                                .css ( {width: '100%', height: '100%'} );

回答by shenhengbin

querySelector:

查询选择器:

return the first matching Element node within the node's subtrees. If there is no such node, the method must return null.

返回节点子树中第一个匹配的元素节点。如果没有这样的节点,则该方法必须返回 null。

querySelectorAll:

查询SelectorAll:

return a NodeList containing all of the matching Element nodes within the node's subtrees, in document order. If there are no such nodes, the method must return an empty NodeList.

返回一个 NodeList,其中包含节点子树中所有匹配的 Element 节点,按文档顺序排列。如果没有这样的节点,该方法必须返回一个空的 NodeList。

The Use :

使用 :

var element = baseElement.querySelector(selectors);
var elementList = baseElement.querySelectorAll(selectors);

Sample :

样本 :

<html>
<body>
    <img class="fb_logo" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo">
</body>
<script type="text/javascript">
    var myImageList = document.querySelectorAll('.fb_logo');
    myImageList[0].src = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";
</script>
</html>

回答by harithski

find the image tag and replace the src attribute.

找到图像标签并替换 src 属性。

var myImage = document.getElementById(idOfImageYouNeedToChange);
myImage.src = "your_image";

Pretty straightforward.

很简单。

回答by Johnny Craig

You can do this very simply with jQuery

您可以使用 jQuery 非常简单地做到这一点

        $('.fb_logo').attr('src','newimage.jpg');

回答by Stann

you have to get the reference to your img element first, better use id instead of a class, since getElementsByClassName is not supported in IE until ie9:

您必须首先获取对 img 元素的引用,最好使用 id 而不是类,因为直到 ie9 IE 才支持 getElementsByClassName:

with raw javascript (there are many ways of doing this. this is just the one):

使用原始 javascript(有很多方法可以做到这一点。这只是一种):

var theImg = document.getElementById('imageId');
theImg.src = 'someNewPath'

with something like jQuery(js library) - you can easily select by class or by id or by tag etc:

使用 jQuery(js 库)之类的东西 - 您可以轻松地按类或按 id 或按标签等进行选择:

$('.yourPicClass').attr('src', 'someNewPath')

回答by filippo

How about using the DOMto find that specific attribute and change it to whatever?

如何使用DOM查找特定属性并将其更改为任何内容?

<html>
    <body>
        <img class="fb_logo img" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo">
    </body>
    <script type="text/javascript">
        var yerImg = document.getElementsByTagName("img");
        yerImg[0].setAttribute("src", "http://goo.gl/JP8bQ");
    </script>
</html>