【问题标题】:How to swap images from side bar to the middle div on clicking on those sidebar images?单击这些侧边栏图像时,如何将图像从侧边栏交换到中间 div?
【发布时间】:2017-05-20 14:18:19
【问题描述】:

我是 JavaScript 新手,我正在尝试构建一个网页,我的侧边栏中有 3 张该产品的图像,中间有一张主图像现在我想在中间获得侧边栏图像用户单击该侧边栏图像。我不知道该怎么做。我已经尝试了几种我在网上找到的方法,其中一种是 1.How to swap image and video to another div?

但这些都不适合我。

【问题讨论】:

  • 请提供您正在使用的页面的相关 HTML、CSS 和 JavaScript。

标签: javascript jquery html css image


【解决方案1】:

您需要做的是将两个图像保存在一个变量中,然后交换它们。看下面的例子

var imgleft,
    imgcenter,
    $center = $(".center img");
$(".sidebar img").click(function(){
  imgleft = $(this).attr("src");
  imgcenter = $center.attr("src");
  $center.attr("src", imgleft);
  $(this).attr("src", imgcenter);
});
.sidebar{
  position: absolute;
  top: 0;
  width: 70px;
  height: 100%;
  background: red;
}
.center{
  width: 80px;
  height: 80px;
  margin:25% auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar">
  <img src="http://placehold.it/70x70">
  <img src="http://placehold.it/70x60">
  <img src="http://placehold.it/70x50">
</div>
<div class="center">
  <img src="http://placehold.it/70x40">
</div>

【讨论】:

    【解决方案2】:

    您可以使用 javascript 的事件处理(在您的每个侧边栏图像上)来解决这个问题。首先在你的html中添加如下java脚本代码:

    <script type="text/javascript">
        function changeToImage1(){
            if(centerImage.src != "[1st-image-url.*]"){
                centerImage.src = "[1st-image-url.*]";
            }
        }
        function changeToImage2(){
            if(centerImage.src != "[2nd-image-url.*]"){
                centerImage.src = "[2nd-image-url.*]";
            }
        }
        function changeToImage3(){
            if(centerImage.src != "[3rd-image-url.*]"){
                centerImage.src = "[3rd-image-url.*]";
            }
        }
    </script>
    

    然后你可以简单地在你的三个侧边栏div的onClick属性中添加上述功能。可以这样做:

    <div id = "first" onclick = "changeToImage1()">
        ...
    </div>
    <div id = "second" onclick = "changeToImage2()">
        ...
    </div>
    <div id = "third" onclick = "changeToImage3()">
        ...
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      相关资源
      最近更新 更多