【问题标题】:Using JavaScript and CSS to create hovers and onclicks使用 JavaScript 和 CSS 创建悬停和点击
【发布时间】:2014-03-20 12:54:29
【问题描述】:

我的页面底部有 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">

【问题讨论】:

  • 再次检查你的代码&lt;a href=""img src="...是错误的

标签: javascript jquery html css image


【解决方案1】:

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

注意:此示例假设您使用的是 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/

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

如果您希望边框停留在您单击的项目上,我还添加了一个“活动”样式。只需将一些 CSS 添加到样式 .active { }

希望对你有帮助

【讨论】:

  • 生活。保护程序。正是我需要的!让边界悬停工作。至于 jQuery,我已经下载了最新的 jQuery 文件,将它放在我的工作文件夹中,并将 src 放在 head 标签中。但是当我点击我的拇指时没有任何反应。
  • 好的,请确保将 JavaScript 代码包装在 $(document).ready() 函数中 - 我编辑了答案以向您展示
  • +1 表示准备功能。 @user3440207:如果您发现答案有帮助,您应该通过投票/接受来表达您的感激之情。
【解决方案2】:

是的,我会在悬停时使用 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);
});

这只是我的想法。我没有测试过。

【讨论】:

猜你喜欢
  • 2016-11-10
  • 1970-01-01
  • 1970-01-01
  • 2013-11-27
  • 1970-01-01
  • 1970-01-01
  • 2014-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多