0

我正在做这个项目,我需要在我们列出了三个产品的地方添加这个功能。

他们最初是 div 的,但将它们更改为 ahref 类以链接整个区域。

悬停时该框必须更改颜色-我已经这样做了。单击时,该框需要更改为另一种颜色-我也这样做了。

我不知道的一件事是如何使第二个框默认为选中状态,然后在选择另一个框时关闭颜色

这是我用于页面的 javascript。

var highlightLink = function () {
    var active = null, colour = '#f6efa2';
    if (this.attachEvent) this.attachEvent('onunload', function () {
        active = null;
    });
    return function (element) {
        if ((active != element) && element.style) {
            if (active) active.style.backgroundColor = '';
            element.style.backgroundColor = colour;
            active = element;
        }
    };

}();

这是其中一个盒子

<a class="productBox1" href="#" border="0" onclick="highlightLink(this);">

我在想我需要在 body 标记中添加一个 onload 函数,但我不知道需要什么代码,而且我还需要在选择另一个框时取消选中它。

任何帮助将不胜感激。

4

2 回答 2

1

听起来你让这比实际上更复杂。试试这个(我假设你所有的 a 标签都有类 productBox1):

$('.productBox1').click(function() {
    $('.highlighted').removeClass('highlighted');
    $(this).addClass('highlighted');
});

然后有一个名为 highlight 的 CSS 类background-color: #f6efa2。您需要jQuery才能使其正常工作。

于 2011-01-13T14:19:49.540 回答
1

如果每个链接都有自己的类,请将其用作 ID:

<a id="productBox1" href="#" border="0" onclick="highlightLink(this);">

对公共属性使用类。要识别单个元素,请使用 ID。

然后您可以将其添加到页面底部(结束<body>标记上方):

<script type="text/javascript">
    highlightLink(document.getElementById('productBox1'));
</script>

或设置

window.onload = function() {
    highlightLink(document.getElementById('productBox1'));
}

<head>.

于 2011-01-13T14:28:08.927 回答