用JavaScript交换两个图像的位置 [英] Swapping the position of two images with JavaScript

查看:215
本文介绍了用JavaScript交换两个图像的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图这样做,如果你点击按钮它会切换图像的位置。然而,它实际上并没有切换位置,而只是改变每个图像ID的src。单击按钮一次就可以工作,但之后图像不再切换。这是我的代码

So i am trying to make it so if you click on the button it will switch the images placement. However it doesnt actually switch the placement but instead just changes the src of each image ID. It works when you click the button once, but after that the images no longer switch. This is my code

function swapImages(){
    var image1 = document.getElementById("image1")
    var image2 = document.getElementById("image2")
    if (image1.src = '/jmurphy9/111/images/earthrise.jpg') {
        image1.src = '/jmurphy9/111/images/earth.jpg';
    } else {
        image1.src = '/jmurphy9/111/images/earthrise.jpg';
}
    if (image2.src = '/jmurphy9/111/images/earth.jpg') {
        image2.src = '/jmurphy9/111/images/earthrise.jpg';
}     else {
        image2.src = '/jmurphy9/111/images/earth.jpg';
}
}

function init(){
    var button1 = document.getElementById("btn1")
    button1.onclick = swapImages;
}

window.onload = init;


推荐答案

问题是 src 属性将具有图像的绝对路径,而不是在检查时的相对路径

The problem is the src property will have the absolute path to the image, not relative one as you are checking

一种可能的解决方案是使用.indexOf()如下所示

One possible solution is to use .indexOf() as given below

function swapImages() {
    var image1 = document.getElementById("image1")
    var image2 = document.getElementById("image2")
    if (image1.src.indexOf('/jmurphy9/111/images/earthrise.jpg')>-1) {
        image1.src = '/jmurphy9/111/images/earth.jpg';
    } else {
        image1.src = '/jmurphy9/111/images/earthrise.jpg';
    }
    if (image2.src.indexOf( '/jmurphy9/111/images/earth.jpg')>-1) {
        image2.src = '/jmurphy9/111/images/earthrise.jpg';
    } else {
        image2.src = '/jmurphy9/111/images/earth.jpg';
    }
}






或者您可以使用 .getAttribute()

if (image1.getAttribute('src') == '/jmurphy9/111/images/earthrise.jpg') {
}






但是既然你想要交换,那么你可以这样做


But since you want to swap, you can just do

function swapImages() {
    var image1 = document.getElementById("image1")
    var image2 = document.getElementById("image2")
    var src = image1.src;
    image1.src = image2.src;
    image2.src = src;
}

演示:小提琴

注意:在你的 if 条件您使用赋值( = )运算符而不是比较运算符( == ),所以 image1.src ='/ jmurphy9/111/images/earthrise.jpg'中,如果应该是 image1.src =='/ jmurphy9/111/images/earthrise.jpg'

Note: In your if condition you are using assignment(=) operator instead of comparison operator(==), so image1.src = '/jmurphy9/111/images/earthrise.jpg' in the if should be image1.src == '/jmurphy9/111/images/earthrise.jpg'

这篇关于用JavaScript交换两个图像的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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