通过单击它来切换div中的背景

时间:2016-09-11 16:57:30

标签: javascript jquery

我一直试图找到一个JavaScript / jQuery,可以在多个div上打开和关闭背景。

我正在创建一个带有菜单的网站,我希望通过点击它们突出显示菜肴。此外,我希望它可以在手机,平板电脑和浏览器上工作。



.full-wrapper {
    width: 100%;
    height: 100%;
}

.menu-wrapper {
    height: 2em;
    width: 24em;
    background: #fff;
    text-align: center;
    line-height: 30px;
    margin: 10px auto;
}

<div class="full-wrapper">
    <div class="menu-wrapper">Click and toggle background between red and white</div>
        <div class="menu-wrapper">Click and toggle background between red and white</div>
            <div class="menu-wrapper">Click and toggle background between red and white</div>
                <div class="menu-wrapper">Click and toggle background between red and white</div>
                    <div class="menu-wrapper">Click and toggle background between red and white</div>
                        <div class="menu-wrapper">Click and toggle background between red and white</div>
</div>
&#13;
&#13;
&#13;

我希望能够使用简单的JavaScript点击以打开和关闭背景。

此外,我还需要能够在浏览器,平板电脑和手机上切换多个div的背景信息。

我一直在尝试一些脚本并修改我发现的内容,但由于我缺乏知识,我需要一些帮助。

2 个答案:

答案 0 :(得分:0)

一些CSS:

.bg-red {
  background:red;
}

一些JavaScript

$('.menu-wrapper').on('click', function(){
    $(this).toggleClass('bg-red');
});

你得到了这个

$('.menu-wrapper').on('click', function(){
	$(this).toggleClass('bg-red');
});
.full-wrapper {
    width: 100%;
    height: 100%;
}

.menu-wrapper {
    height: 2em;
    width: 24em;
    background: #fff;
    text-align: center;
    line-height: 30px;
    margin: 10px auto;
}
.bg-red {
  background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="full-wrapper">
    <div class="menu-wrapper">Click and toggle background between red and white</div>
        <div class="menu-wrapper">Click and toggle background between red and white</div>
            <div class="menu-wrapper">Click and toggle background between red and white</div>
                <div class="menu-wrapper">Click and toggle background between red and white</div>
                    <div class="menu-wrapper">Click and toggle background between red and white</div>
                        <div class="menu-wrapper">Click and toggle background between red and white</div>
</div>

答案 1 :(得分:0)

&#13;
&#13;
$('.menu-wrapper').on('click touchstart', function(){
    $(this).toggleClass('bg-red');
});
&#13;
&#13;
&#13;

在移动设备上工作