我在学习 javascript 时遇到了一个关于使用 onclick 事件的视频,(https://www.youtube.com/watch?v=XQEfWd1lh4Q&list=PL4cUxeGkcC9i9Ae2D9Ee1RvylH38dKuET&index=41&t=23s)。基本上,这家伙可以扩展以显示一张卡片它切断的部分内容。我能够跟上并且只是通过观看视频才有所了解。所以为了加深我的理解,我决定重新编码视频中显示的内容,而不参考它。
我有点得到了我想要的东西,但有一件小事让我感到沮丧。当我运行我的代码时,我得到了带有“显示更多”按钮的浓缩卡片(这很好),但是当我按下按钮时,卡片会展开但按钮仍然显示“显示更多”(这是它开始变坏),只有当我第三次按下按钮以压缩卡片时,按钮才会显示“Show Less”。
var contentDiv = document.querySelector('.content');
var button = document.querySelector('.button');
button.onclick = function(){
if(contentDiv.className == 'content'){
contentDiv.classList.add('appear');
button.innerHTML = 'Show More';
} else if(contentDiv.className == 'content appear'){
contentDiv.classList.remove('appear');
button.innerHTML = 'Show Less';
}
};
*{
margin: 0;
padding: 0;
}
body{
background: #a1a1a1;
}
.group{
margin-top: 10%;
display: flex;
flex-flow: column nowrap;
align-items: center;
}
.content{
background: #dedede;
border-radius: 10px;
width: 250px;
height: 300px;
overflow: hidden;
color: #2e2e2e;
background: #e8e8e8;
transition: all .5s;
}
.appear{
height: 530px;
color: #e8e8e8;
background: #2e2e2e;
}
.content p{
margin: 10px;
}
.button{
margin: 10px;
background: #f0ca62;
padding: 5px;
border-radius: 10px;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<title>Events</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<div class="group">
<div class="content">
<p>width inflation scrape lamp continuation insistence proof pioneer trait
vegetation dorm bring ball charter joy brick cabinet nest use economist
width inflation scrape lamp continuation insistence proof pioneer trait
vegetation dorm bring ball charter joy brick cabinet nest use economist
width inflation scrape lamp continuation insistence proof pioneer trait
vegetation dorm bring ball charter joy brick cabinet nest use economist
</p>
<p>width inflation scrape lamp continuation insistence proof pioneer trait
vegetation dorm bring ball charter joy brick cabinet nest use economist
width inflation scrape lamp continuation insistence proof pioneer trait
vegetation dorm bring ball charter joy brick cabinet nest use economist
</p>
<p>width inflation scrape lamp continuation insistence proof pioneer trait
vegetation dorm bring ball charter joy brick cabinet nest use economist
</p>
</div>
<a class="button">Show More</a>
</div>
<script type="text/javascript" src="./js/script.js"></script>
</body>
</html>
似乎 show more 和 show less 按钮颠倒了,试试这个:
button.onclick = function(){
if(contentDiv.className == 'content'){
contentDiv.classList.add('appear');
button.innerHTML = 'Show Less';
} else if(contentDiv.className == 'content appear'){
contentDiv.classList.remove('appear');
button.innerHTML = 'Show More';
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句