使用JavaScript和CSS创建悬停和点击

Using JavaScript and CSS to create hovers and onclicks

本文关键字:悬停 CSS JavaScript 使用 创建      更新时间:2023-09-26

我的页面底部有4个缩略图,上面有一个主要的大图像。我希望能够点击缩略图,并有它加载到大图。此外,我希望能够悬停在缩略图上,并在其周围出现黑色边框。

我有40个页面,有完全相同的设置(4拇指,1主图像),但所有不同的图像(产品)。拇指都在"class="bottom-pic"。

这似乎很容易,但也许我错了。我在想CSS悬停,JS点击?我是JS的新手。

源代码如下:

<a href=""img src="images-large/cobra-dark-wood.jpg" alt="" id="main-photo" >
<img src="images-large/cobra-dark-wood.jpg" alt="" name="photo-bottom-one"  class="bottom-pic" id="photo-bottom-one">
<img src="images-large/cobra-dark-wood-one.jpg" alt="" id="photo-bottom-two"  class="bottom-pic">
<img src="images-large/cobra-black.jpg" alt="" id="photo-bottom-three"  class="bottom-pic">
<img src="images-large/cobra-black-one.jpg" alt="" name="photo-bottom-four"  class="bottom-pic" id="photo-bottom-four">

根据您的代码,并且不需要锚标记等,这里是您可以使用的JavaScript。

NB:这个例子假设你正在使用jQuery

$(document).ready(function() {    
    $('.bottom-pic').on('click', function(){
        $('.bottom-pic').removeClass("active"); //Removes class from all items
        $(this).addClass("active");  //Adds class only to the currently clicked on item
        $('#main-photo').attr('src', $(this).attr('src')); //Changes the source of the image tag
    });
});

为了看到一个工作的演示,我为您创建了这个小提琴。

http://jsfiddle.net/2ZgjR/

请注意,图像不匹配,因为它们是从服务器动态加载的,但效果正是您所要求的,只需使用此代码与您的图像!

我还添加了一个"active"样式,如果你想在你点击的项目上保持边框。只需添加一些CSS样式.active { }

希望能有所帮助

是的,我将使用CSS在悬停的边界。你可能不得不使用box-sizing: border-box来确保事情不会跳来跳去。

首先,你的主图像应该像这样:
<a href="whatever_link"> 
    <img src="images-large/cobra-dark-wood.jpg" alt="" id="main-photo">
</a>

由于您正在使用jQuery,因此在单击时将切换出主图像的源将非常容易。像这样:

$('.bottom-pic').on('click', function(){
    var imgSrc = $(this).attr('src');
    $('#main-photo').attr('src', imgSrc);
});

那是我刚想到的。我还没有测试过