如何使用 javascript/jquery 动态更改图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6973927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:32:45  来源:igfitidea点击:

How to dynamically change an image using javascript/jquery?

javascriptjqueryimagedynamic

提问by Prateek

So,i have this http://jsfiddle.net/ithril/UjGhE/1/Please check it out.

所以,我有这个http://jsfiddle.net/ithril/UjGhE/1/请检查一下。

What i'm trying here is to change the main image img tag's src dynamically to the same src attribute of the image that is clicked. In short whichever image is clicked,it is displayed in the bigger window which has an id="main-photo".

我在这里尝试的是将主图像 img 标签的 src 动态更改为单击的图像的相同 src 属性。简而言之,无论单击哪个图像,它都会显示在 id="main-photo" 的更大窗口中。

回答by Kalle H. V?ravas

I see my original code has made it this far :) Because nobody has gotten accept, I will try my best. I will again give you some pointers on general matter:

我看到我的原始代码已经成功了 :) 因为没有人接受,我会尽力而为。我将再次给你一些关于一般问题的提示:

  1. Your hyperlink tags (<a>) are unclosed. This will surely generate a validation error. You can train your html skills be validating yourself regularly(sounds dirty right?)
  2. In .main-photo img {}the position:relative:is not closed with ;'
  3. In your .slider-large-image li img {}, margin: 10pxwas not closed!
  1. 您的超链接标签 ( <a>) 未关闭。这肯定会产生验证错误。你可以训练你的 html 技能,定期验证自己(听起来很脏,对吧?)
  2. .main-photo img {}所述position:relative:未封闭;”
  3. 在你的.slider-large-image li img {}margin: 10px没有关闭!

NOTES

笔记

  • You could have added this question to your original one. I would have happily added this feature :)
  • I again corrected your code a little.
  • Is there a solid reason for using hyperlinks in your carousel list? I removed the tags, since they made things unnecessarily complicated. You should do the same with the previous and next triggers.
  • I'm not going to fix the layouting. You can figure it yourself out :)
  • Miley rocks!
  • I added default image, so when the page is loaded for the first time -- there wouldn't be a empty container.
  • 您可以将这个问题添加到您原来的问题中。我很乐意添加此功能:)
  • 我再次更正了您的代码。
  • 在轮播列表中使用超链接是否有充分的理由?我删除了标签,因为它们使事情变得不必要地复杂。您应该对上一个和下一个触发器执行相同的操作。
  • 我不会修复布局。你可以自己弄清楚:)
  • 麦莉摇滚!
  • 我添加了默认图像,所以当第一次加载页面时——不会有空容器。

Live demo

现场演示

http://jsfiddle.net/hobobne/K439d/

http://jsfiddle.net/hobobne/K439d/

Full version code:

完整版代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>How to dynamically change an image using javascript/jquery? - Kalle H. V?ravas</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <style>
        html, body {margin: 0px; padding: 0px;}
                html, body, div, th, td, p, a {font-family: "Comic Sans MS", cursive; font-size: 12px; color: #000000;}
                .cb {clear: both;}
                #wrapper {width: 400px; margin: 0px auto;}
                    .main-photo{width: 80%; height: 400px; position: relative; border: 1px solid #000000;}
                        .main-photo img {width:100%; height:100%; position:relative; top: 0; left: 0px;}
                    .main-slider {float: left; position: relative; margin-bottom: 10px; border: 0px solid #000; top: 25px; left: 0px; -moz-border-radius: 5px; border-radius: 5px; -moz-box-shadow: 0px 0px 30px 1px #999; -webkit-box-shadow: 0px 0px 30px 1px #999; box-shadow: 0px 0px 30px 1px #999; padding: 0px; color: #FFF; text-align: center; text-decoration: none; /*background-color: #CCC;*/}
                    .window {width: 700px; height: 230px; overflow: hidden; position: relative;}
                        .slider-large-image {position: relative; overflow: hidden; float: left; list-style-type: none; margin: 0px; padding: 0px;}
                            .slider-large-image li {margin: 0px; padding: 0px; float: left; display: inline-block;}
                                .slider-large-image li img {float: left; width: 200px; height: 150px; margin: 10px; cursor: pointer;}
                    .slider-pager {position: relative; z-index: 2; margin: -40px auto 0px;}
                        .slider-pager a {margin: 0px 2px; padding: 2px; text-align: center; text-decoration: none; font-size: 20px; font-weight: bold; color: #ccc;}
                            .slider-pager a:hover,
                            .slider-pager a:active {background-color: #999; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px;}
                            .slider-pager a:hover {color: black;}
                            .slider-pager a.active {/* background-color and border-radius used to be here.. */}
    </style>
</head>
<body>
    <div id="wrapper">
        <div class="main-photo">
            <img id="mainphoto" src="http://www.insanemom.net/wp-content/uploads/miley-cyrus-smoking-bong.jpg" />
        </div>
        <div class="main-slider">
            <div class="window">
                <ul class="slider-large-image">
                    <li><img src="http://images.sneakhype.com/wp-content/uploads/2010/12/Miley-Cyrus-300x200.jpg" /></li>
                    <li><img src="http://wa2.www.3news.co.nz/Portals/0-Articles/185340/miley-cyrus_reuters_420.jpg?width=300" /></li>
                    <li><img src="http://cdn.buzznet.com/media/jjr/headlines/2009/03/miley-cyrus-ryan-seacrest.jpg" /></li>
                    <li><img src="http://images.smh.com.au/2010/12/29/2112265/miley_cyrus_400-300x200.jpg" /></li>
                </ul>
            </div>
            <div class="slider-pager"><a href="#" id="b">&lsaquo;</a><a href="#" id="f">&rsaquo;</a></div>
        </div>
        <br class="cb" />
    </div>
    <script>
        $(document).ready(function() {
            var imagewidth = $('.slider-large-image li').outerWidth();
            var imagesum = $('.slider-large-image li img').size();
            var imagereelwidth = imagewidth * imagesum;
            $(".slider-large-image").css({'width' : imagereelwidth});
            $('.slider-large-image li:first').before($('.slider-large-image li:last'));
            $('.slider-large-image').css({'left' : '-' + imagewidth + 'px'});
            rotatef = function (imagewidth) {
                var left_indent = parseInt($('.slider-large-image').css('left')) - imagewidth;
                $('.slider-large-image:not(:animated)').animate({'left' : left_indent}, 500, function() {
                    $('.slider-large-image li:last').after($('.slider-large-image li:first'));
                    $('.slider-large-image').css({'left' : '-' + imagewidth + 'px'});
                });
            };
            rotateb = function (imagewidth) {
                var left_indent = parseInt($('.slider-large-image').css('left')) + imagewidth;       
                $('.slider-large-image:not(:animated)').animate({'left' : left_indent}, 500, function(){               
                    $('.slider-large-image li:first').before($('.slider-large-image li:last'));
                    $('.slider-large-image').css({'left' : '-' + imagewidth + 'px'});
                });
            };
            $(".slider-pager a#b").click(function () {
                rotateb(imagewidth);
                return false;
            });
            $(".slider-pager a#f").click(function () {
                rotatef(imagewidth);
                return false;
            });
            $(".slider-large-image li img").click(function() {
                $(".main-photo img").attr("src", $(this).attr('src'));
            });
        });
    </script>
</body>
</html>

回答by smdvlpr

It's really simple to do this using jQuery. When the user clicks on an <img>tag, you'll have access to thisinside the callback function. Simply take $(this).attr('src')and set the source of $('#main-photo')to it like so:

使用 jQuery 做到这一点非常简单。当用户点击<img>标签时,您将可以访问this回调函数内部。简单地获取$(this).attr('src')并设置它的来源,$('#main-photo')如下所示:

$('img').click(function(){
    $('#main-photo').attr('src', $(this).attr('src'));
});

-

——

It looks like in your code, you're using .main-photo img, which should also work. I'm looking at it more now.

看起来在您的代码中,您正在使用.main-photo img,这也应该有效。我现在看多了。

-

——

EDIT, after reviewing your code, you seem to have many missing </a>s along with other errors. Here is an updated and working version (minus the CSS and extra javascript):

编辑,在查看您的代码后,您似乎缺少许多</a>s 以及其他错误。这是一个更新的工作版本(减去 CSS 和额外的 javascript):

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('.slider-large-image a img').click(function() {
        $('img#mainphoto').attr('src, $(this).attr('src'));
    });
});
</script>
<div id="wrapper">
    <div class="main-photo"><img id="mainphoto" src="" /></div>
    <div class="main-slider">
        <div class="window">
            <ul class="slider-large-image">
                <li><a href=""><img src="http://images.sneakhype.com/wp-content/uploads/2010/12/Miley-Cyrus-300x200.jpg" /></a></li>
                <li><a href=""><img src="http://wa2.www.3news.co.nz/Portals/0-Articles/185340/miley-cyrus_reuters_420.jpg?width=300" /></a></li>
                <li><a href=""><img src="http://cdn.buzznet.com/media/jjr/headlines/2009/03/miley-cyrus-ryan-seacrest.jpg" /></a></li>
                <li><a href=""><img src="http://images.smh.com.au/2010/12/29/2112265/miley_cyrus_400-300x200.jpg" /></a></li>
            </ul>
        </div>
        <div class="slider-pager"><a href="#" id="b">&lsaquo;</a><a href="#" id="f">&rsaquo;</a></div>
    </div>
    <br class="cb" />
</div>

回答by GeekTantra

Change this part of your JS code:

更改这部分 JS 代码:

$(".slider-large-image li a img").click(function() {

        $(".main-photo img").attr("src",$(this).attr('src'));

    });

to:

到:

$(".slider-large-image li a").click(function() {        
   $(".main-photo img").attr("src",$(this).find("img").attr("src"));
   return false;
});

It should work fine. Eg: http://jsfiddle.net/UjGhE/23/

它应该可以正常工作。例如:http: //jsfiddle.net/UjGhE/23/

回答by slobodan

$("ul.slider-large-image li a").click(function(e){
    e.preventDefault();      // prevent changing url
    $("#mainphoto").attr('src',$(this).children('a').attr('src')); //show clicked photo as main
});

回答by Joey

All you have to do is remove the hrefattribute from your links. When clicked, this causes the page to reload. However, this attribute is also responsible for the cursor to turn into a pointer, so you'll have to manually assign one in CSS: a { cursor: pointer }

您所要做的就是href从链接中删除该属性。单击时,这会导致页面重新加载。但是,该属性还负责将光标变成指针,因此您必须在 CSS 中手动分配一个:a { cursor: pointer }

Clicking on the img's now would load said image in your main image holder, without the page reloading, which caused your problem.

现在单击 img 将在您的主图像持有者中加载所述图像,而不会重新加载页面,这会导致您的问题。

I would clean up the html if i were you though, cause there are a lot of unclosed tags.

如果我是你,我会清理 html,因为有很多未关闭的标签。