【问题标题】:Javascript, CSS & HTML: How to swap images using onclick etc.?Javascript、CSS 和 HTML:如何使用 onclick 等交换图像?
【发布时间】:2020-11-03 04:43:06
【问题描述】:

我在 JS、HTML、CSS 中有以下代码,目前看起来像这样。 (https://jsfiddle.net/sidsingh29/591hfwLd/33/)

项目有 2 个对象,位置分别是:

  1. 红圈:https://drexel.qualtrics.com/CP/Graphic.php?IM=IM_ezDZcerD82eHf81
  2. 绿圈:https://drexel.qualtrics.com/CP/Graphic.php?IM=IM_3XmJ5y3lOBQD469

我想要什么:

  1. 每次单击圆圈时,两个对象应交替出现。例如。红圈 --> 点击 ---> 绿圈。 ....(R,G,G,G,R,R,G.....)

  2. 圆的移动应该始终是随机的,在给定对话框的尺寸上的任何位置。它基本上就像一个游戏,每次点击它时,球应该会交替颜色并四处移动。这两种颜色基本上是我想要使用的两个对象(图像)。

  3. 代码必须使用 HTML、CSS、JS 这些语言

代码

$('#test').click(function() {
        var docHeight = $(document).height(),
            docWidth = $(document).width(),
            $div = $('#test'),
            divWidth = $div.width(),
            divHeight = $div.height(),
            heightMax = docHeight - divHeight,
            widthMax = docWidth - divWidth;
        
        $div.css({
            left: Math.floor( Math.random() * widthMax ),
            top: Math.floor( Math.random() * heightMax )
        });
    });
#test {
        position:absolute;
        width:100px;
        height:70px;
        background-color:white;
    }
    
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"><img id = "item" src="https://drexel.qualtrics.com/CP/Graphic.php?IM=IM_ezDZcerD82eHf81" style="width: 51px; height: 51px;"></div>

【问题讨论】:

  • 感谢您的编辑。您是否也为我的问题找到了解决方案?

标签: javascript html css node.js


【解决方案1】:

const toggleImage = () => {
    const images = [
        "https://drexel.qualtrics.com/CP/Graphic.php?IM=IM_ezDZcerD82eHf81",
        "https://drexel.qualtrics.com/CP/Graphic.php?IM=IM_3XmJ5y3lOBQD469"
    ];
    let image = Math.random() >= 0.5 ? images[0] : images[1];
    $("#test #item").attr("src", image);
};

$('#test').click(function() {
        var docHeight = $(document).height(),
            docWidth = $(document).width(),
            $div = $('#test'),
            divWidth = $div.width(),
            divHeight = $div.height(),
            heightMax = docHeight - divHeight,
            widthMax = docWidth - divWidth;
        
        $div.css({
            left: Math.floor( Math.random() * widthMax ),
            top: Math.floor( Math.random() * heightMax )
        });
        toggleImage();
    });
#test {
        position:absolute;
        width:100px;
        height:70px;
        background-color:white;
    }
    
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"><img id = "item" src="https://drexel.qualtrics.com/CP/Graphic.php?IM=IM_ezDZcerD82eHf81" style="width: 51px; height: 51px;"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    相关资源
    最近更新 更多