简体   繁体   English

javascript加载图像源使页面闪烁

[英]javascript to load image source keeps the page blinking

I am new to Javascript, I try to make a simple program which changes image source on button click. 我是Java语言的新手,我尝试制作一个简单的程序,单击按钮即可更改图像源。 the image is being loaded but immediately deleted. 该图像正在加载,但立即被删除。 it works only if I call the image source loading function from the onload event of the body. 仅当我从主体的onload事件调用图像源加载功能时,此方法才有效。 but than the result is wromg: it loads all the page with the wrong image source and than call the onload function -> resulted in page that blinks twice until fully loaded. 但是结果是错误的:加载所有页面的图片来源不正确,然后调用onload函数->导致页面闪烁两次直到完全加载。 My final goal is to allow one initial images loading and than change images on button click from javascript (not calling the server). 我的最终目标是允许加载一个初始图像,然后从javascript单击按钮(而不是调用服务器)更改图像。 Thanks in advance 提前致谢

function load() {
        document.getElementById("mainImg").src = 'Koala.jpg';
    }

<button type="submit" name="btn0101" value="btn" onclick="load()" >
                            <img src="iconUnavail.png" id="mainImg" />
                            </button>

I assume you are trying to preload images. 我认为您正在尝试预加载图像。 This is how you do that. 这就是您的做法。

var myImage = new Image(100, 100)
myImage.src = "mainImg"

Then when you are ready (button click), just swap out the src and the image will appear immediately. 然后,当您准备好(单击按钮)时,只需换出src,图像将立即显示。


That said, a better way would be to use sprites. 也就是说,更好的方法是使用Sprite。

<button>的“ submit”调用将强制重新加载页面-尝试删除该页面。

What you can do is bind your event to the onclick event in the button itself like so 您可以做的是将事件绑定到按钮本身中的onclick事件,如下所示

jsFiddle https://jsfiddle.net/a3pv8j71/1/ jsFiddle https://jsfiddle.net/a3pv8j71/1/

Html HTML

<img id="mainImg" src="http://www.squirrelsandmore.com/media/wysiwyg/feline_cat_img.jpg">
<button type="submit" onclick="changeImage()">Change img
    </button>

Javascript Java脚本

function changeImage() {
    document.getElementById("mainImg").src = 'http://photos.jibble.org/Experimental/Flying%20Cat/IMG_4821%20Flying%20cat%20.JPG';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM