一个函数可以规则多个按钮,然后再规则一些按钮

One function to rule multiple buttons, and then some

本文关键字:按钮 规则 然后 一个 函数      更新时间:2023-09-26

我有7个按钮。它们分布在背景图像的顶部并与之交互。它们是绝对放置的。我创建了一个jQuery函数来为其中一个按钮的高度设置动画。按钮向上展开。点击此处查看:http://hdpano.no/bf/newindex.html然后单击左上角名为Deck 8的按钮。

我希望这个函数能处理所有的按钮,但也有一些变量。每个按钮的基线各不相同,当我扩展高度时,我需要从中减去。如果有人点击另一个按钮,我也希望关闭任何其他打开的按钮。

这是jQuery代码:

jQuery(document).ready(function() {
$('#link8').toggle(
function()
{
  $('#deck8').animate({height: "25px",top:"202"}, 500);
},
function()
{
$('#deck8').animate({height: "150",top:"76"}, 500);
});
});

这个功能非常基本,我已经把它从我所有的尝试中剥离出来,让它与其他按钮一起工作。

这就是您想要的。将页面中的代码替换为。。。

<script type="text/javascript">
    jQuery(document).ready(function() {
        $('.link').click(function() {
            var $me = $(this);
            if ($me.height() == 150) {
                $me.animate({height: "25px",top:"+=126"}, 500);
            } else {
                $(".link").each(function() {
                    if ($(this) != $me) {
                        if ($(this).height() == 150) {
                            $(this).animate({height: "25px",top:"+=126"}, 500);
                        }
                    } 
                });
                $me.animate({height: "150px",top:"-=126"}, 500);
            }
        });
    });
</script>

您可以使用+=和-=来切换位置,这样它就使用相对定位,而不是绝对定位,这样代码就会影响带有类"link"的页面上的所有div。

切换函数中的

this将是被单击的元素。

以下是我要做的:

  • 移除<br/>标签。使用边距/填充来实现间距。

  • 基本上,您想要将元素".link"(容器)展开/折叠为所包含的<ul>的高度。

  • 在animate函数中使用"+="或"-="可以自动添加/删除指定的值。

  • 当你的按钮开始折叠时,你应该反转切换中的两个功能

这里有一个更通用的代码:

jQuery(document).ready(function() {
    // on click of any link with class ".linkContent"
    $('.linkContent').toggle(
    function() {
            // get the parent ".link" container
        var $parent = $(this).parent(),
            // get the full height of the <ul> to show/hide + the height of the link
            h = $parent.find('ul').outerHeight() + $(this).outerHeight();
        // animate using += and -= to avoid setting explicit values
        $parent.animate({ height: '+=' + h, top: '-=' + h }, 500);
    },
    function() {
        var $parent = $(this).parent(),
            h = $parent.find('ul').outerHeight() + $(this).outerHeight();
        $parent.animate({ height: '-=' + h, top: '+=' + h }, 500);
    });
});

下面的演示展示了代码的作用。你可能需要稍微调整一下,以获得添加/删除的确切高度,但你会想到:

DEMO

您要做的是向每个按钮添加一个类,例如.deck,然后切换.deck'. Inside the toggle function use$(this)`以引用当前按钮。