如何用javascript更改网站图像? [英] How to change a website image with javascript?

查看:168
本文介绍了如何用javascript更改网站图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working with my first Greasemonkey script.

对于有徽标的网站,我想将图像更改为我创建的图像,我想知道我是怎么做到的?

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?

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

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

感谢您的帮助!

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

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

<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">

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

Here is the javascript code i tryed and didnt work:

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


推荐答案

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

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.).

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

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

还要注意它使用jQuery - 其中编写GM脚本是天赐之物。

最后:请注意我避开Facebook,只知道一个徽标位置(加上OP报告的位置。如果有新的/不同的位置,请处理他们以类似的方式。


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.

// ==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%'} );

这篇关于如何用javascript更改网站图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆