如何基于'onclick事件'加载图像

时间:2017-02-23 12:44:04

标签: javascript html

我正在创建一个交互式,我在页面上有三种颜色作为div。一旦用户点击颜色,我希望图像在下一部分加载为用户选择的颜色。我创造了三种不同颜色的夹克,我需要知道如何根据他们选择的选项加载夹克的颜色。

<div id="page-colour">
    <h1>About your jacket.</h1>
    <h2>Select your leather jacket colour.</h2>
        <div class="col-md-offset-3 col-md-2">
            <div class="black-button colourButton">
                <p>Black</p>
            </div>
        </div>

        <div class="col-md-2">                  
            <div class="brown-button colourButton">
                <p>Brown</p>
            </div>
        </div>

        <div class="col-md-2">                  
            <div class="white-button colourButton">
                <p>White</p>
            </div>
        </div>

</div>

<div id="page-build">

   <div class="theJacket col-xs-3 col-md-9">
        <img class="" src="img/black-jacket.png" class="img-responsive" alt="Black Leather Jacket" width="600" height="750"/>
    </div>

</div>

这就是我加载下一页的方式:

$(document).ready(function(){
    $('.intro-button').click(function(){
        transition("#page-jacket","fade");
    });


function transition(toPage, type){
    var toPage = $(toPage),
        fromPage = $("#pages .current"); // store the page that is currently showing

    toPage
    .addClass("current " + type + " in")
    .one("msAnimationEnd animationend oAnimationEnd", function(){  // listens for when the animation has finished
      fromPage.removeClass("current " + type + " out" );
      toPage.removeClass(type + " in");
    });
  fromPage.addClass(type + " out ");
}

1 个答案:

答案 0 :(得分:0)

有多种方法可以做到这一点。一种显而易见的方法是将图像URL存储在夹克div中的额外数据元素中:

<div class="col-md-offset-3 col-md-2">
    <div class="black-button colourButton" data-imageurl="img/black-jacket.png">
        <p>Black</p>
    </div>
</div>

然后您更新脚本,以便当访问者点击夹克颜色时,图像会刷新:

$(document).ready(function() {
  $('.colourButton').on('click', function () {
     $('.theJacket img').attr('src', $(this).data('imageurl'));
  });
});

或为图片提供ID,并通过其ID而非.theJacket img

直接调用

Plnkr:https://plnkr.co/edit/McyGeEv1o8ysf9ruj8cr?p=preview