CSS Accordion -> Adding jquery to change “hover” t

2019-07-24 14:08发布

I'm using a pure css accordion, which works as I intended it, with a "hover" function which opens the slides. However I was looking to change this to a toggle so that when you click, it opens, when you click it closes. I found this thread which explained how to do it and provided the JS to do so:

Convert hover accordion to onclick

However after adding jquery and the script to my html, it doesn't seem to work:

(idk why the title on the accordion doesn't appear where it should, this is only an issue on fiddle, it works as a webpage.)

http://jsfiddle.net/7Q8ea/

$('h3','.accordion ul li').on('click',function() {
    $(this).closest('li').toggleClass('hover').siblings().removeClass('hover');
});

I'm guessing the js that I took from the thread above is wrong somehow, but I'm not sure where. I've tried to make sure it's relating to the css I'm using, but I'm not a coder, so I may be missing something obvious.

p.s. the JS above and in the fiddle is taken "as is" from the other thread, I have tried removing the 'h3' etc. to make sure it wasn't that which was causing a problem, but apparently not.

edit: Sorry, forgot to mention, this must be IE8 compatible.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Pure CSS accordion</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body id="home">
<ul class="accordion" id="vertical">
<li class="slide-01">
<div>
<h2>Title goes Here</h2>
<br /> <img src="http://i.imgur.com/ezY207l.gif" height="125" width="180" /> <taxt>Text here</taxt></div>
</li>
</ul>
      <script src="jquery.js"></script>
      <script $('h3','.accordion ul li').on('click',function() {
    $(this).closest('li').toggleClass('hover').siblings().removeClass('hover');
});
</script>
</body>
</html>

Edit2: Posted my HTML above incase I've made an error here. Maybe. Probably. Edit3: Okay, seems to be a problem with me having the JS in the body, same if I change it to in the head.

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-24 14:33

You had two problems. Your jQuery selector was incorrect and you needed to update your :hover css selector changing it to a .hover class:

New Selector:

$('h3, ul.accordion  li').on('click',function() {
//$('h3','.accordion ul li').on('click',function() {

New Css

/*.accordion:hover li{*/
#vertical .hover li{
    width:100%;
}
/*.accordion:hover{*/
#vertical .hover{
    height:200px;
    width:100%;
}

jsFiddle

查看更多
孤傲高冷的网名
3楼-- · 2019-07-24 14:38

The script you need is

   $('.accordion li h2').on('click',function() {  
$(this).parents('li').toggleClass('hover').siblings().removeClass('hover');
    });

You then need to update the css so that it uses the .hover instead of :hover

New fiddle: http://jsfiddle.net/fLkaG/

查看更多
登录 后发表回答