我有被放置由外部脚本的图像:页面加载后交换(替换)图像src?
<img src="https://example1.com/image1.png" id="image1">
我需要交换(替换)图片src与我的形象,
原始脚本加载后。
我找到了通过单击或鼠标悬停来更改图像src或更复杂的图像集的解决方案,但是我可以在页面加载时为单个图像强制进行图像交换而无需额外操作吗? 在此先感谢您的建议。
我有被放置由外部脚本的图像:页面加载后交换(替换)图像src?
<img src="https://example1.com/image1.png" id="image1">
我需要交换(替换)图片src与我的形象,
原始脚本加载后。
我找到了通过单击或鼠标悬停来更改图像src或更复杂的图像集的解决方案,但是我可以在页面加载时为单个图像强制进行图像交换而无需额外操作吗? 在此先感谢您的建议。
如果我得到你的权利,你要执行的页面加载的变化:
$(function() {
$("#image1").attr("src", "https://example2.com/image2.png")
})
这工作完美。谢谢! – carpeperdiem
在这里你去,
$(function(){
$('#image1').attr('src', $('#image2').attr('src'));
})
说明:
$('#image2').attr('src')
将返回src
您的图片属性存在于img id=image2
中,并且src将被设置在src中的img id=image1
,这将被自动触发,因为jQuery确保ttribute,
$(function(){
//wherever you write here will be executed only after DOM load, no external trigger needed
})
希望它能帮助:)
谢谢你分享这个。我从这里的每个人都学到了很多! – carpeperdiem
@carpeperdiem,如果你喜欢,你可以随时通过提高我的答案来感谢我:D –
你需要这样做的window.load
事件。
$(document).ready(function() {
$('#image1').attr('src', 'http://placehold.it/150x350');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://placehold.it/350x150" id="image1">
有时要操纵的照片,并用$(文件)。就绪() 你将不能够这样做,如果游客没有图像 已经加载。在这种情况下,您需要在图像加载完成时初始化jQuery 对齐函数。
但它是无用的。用户几乎看不到原始图像(它将很快交换)。
$(window).load(function() {
$('#image1').attr('src', 'http://placehold.it/150x350');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://placehold.it/350x150" id="image1">
谢谢你分享这个。我从这里的每个人都学到了很多! – carpeperdiem
如果你想快速改变图像尽可能可以使用DOMNodeInserted
事件。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<script>
// Swap out the image as soon as the DOM is inserted
$('body').on('DOMNodeInserted', '#image1', function(e) {
$("#image1").attr("src", "http://placehold.it/100x100").attr("id", "image2");
});
</script>
<div id="js-putImageHere"></div>
<script>
// Here is the external code that loads the image you don't want
$("#js-putImageHere").html('<img src="http://placehold.it/350x150" id="image1">');
</script>
</body>
谢谢你分享这个。我从这里的每个人都学到了很多! – carpeperdiem
这种或那种方式,你需要能够告诉这个时候其他脚本放在图像;我们没有足够的信息来知道这个脚本函数是发生在“在页面加载”,“在文档加载”,“在图书馆加载”等等。检查有问题的脚本以查看它是否提供“在加载”或“就绪“回调参数。 – Katana314
谢谢你的回复。我不知道如何检查这个。有没有方法来尝试图像src替换,看看它是否工作? – carpeperdiem