更改菜单图像

时间:2016-11-14 18:18:23

标签: javascript jquery html css

我需要在单击菜单按钮后更改背景图像,但CSS:活动属性不适用于它,仅在点击时,我需要将其保留为图像,直到它们为止再次点击它。

HTML

<nav class="clearfix">
   <div class="menu">
      <ul style="list-style-type:none;">
         <li>
             <a href="home.html">Home</a>
          </li>
          <li>
             <a href="about.html">About</a>
          </li>
          <li>
             <a href="slide.html">Before/After</a>
          </li>
          <li>
             <a href="fac.html">Facilities</a>
          </li>
          <li>
             <a href="contact.html">Contact</a>
          </li>
          <li>
             <a href="staff.html">Staff</a>
          </li>
      </ul>
   </div>
   <div class="site-wrapper">
      <div class="header">
          <a><div class="menu-trigger" title="Menu"></div></a>
      </div>
   </div>
   <script src="testing.js" type="text/javascript">
   </script>
</nav>

CSS

.menu-trigger {
    background-image:url("http://download.seaicons.com/icons/custom-icon-design/flatastic-2/512/usb-icon.png");
    background-position:center;
    background-size:100% 100%;
    background-repeat: no-repeat;
    width:50px;
    height:50px;
    left: -150%;
    transform:rotate(-135deg);
    position:relative;
}

.menu-trigger:hover{
    cursor: pointer;
}

JS

$('a .menu-trigger').on('click', function() {
    $('.menu').toggleClass('open', 300, 'easeOutQuad');
});

2 个答案:

答案 0 :(得分:1)

使用jquery - 更改按钮背景图片 检查代码段

&#13;
&#13;
$(document).ready(function() {

  $(".menu-trigger").click(function() {
        
     $(".menu-trigger").toggleClass("open")

  })

})
&#13;
.menu-trigger {
    background-image:url("http://download.seaicons.com/icons/custom-icon-design/flatastic-2/512/usb-icon.png");
    background-position:center;
    background-size:100% 100%;
    background-repeat: no-repeat;
    width:50px;
    height:50px;
    left:0%;
    transform:rotate(-135deg);
    position:relative;
    cursor:pointer
}

.open{
  background-image:url("http://download.seaicons.com/icons/custom-icon-design/flatastic-2/512/help-desk-icon.png");
  
  }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="site-wrapper">
      <div class="header">
          <a><div class="menu-trigger" title="Menu"></div></a>
      </div>
   </div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

为什么不在课堂上为每个人设置背景图片,然后只是切换?

.pre_click { 
     background-image:url(".../image_1.png");
 }
.post_click { 
     background-image:url(".../image_2.png");
 }

然后切换

 $('.menu').on('click', function() { 
    $('.menu').toggleClass('pre_click post_click')
}) 

确保您设置了要应用于&#39;菜单的默认课程。项目所以它将正确切换。