原生js(DOM2级事件)实现常见的抽屉下拉,收起效果
1.Demo展示:
2 . Html布局:
<div class="drawer">
<div class="drawer-content">
<p>Youth is not a time of life; it is a state of mind. It is not a matter of rosy cheeks, red lips and supple knees. It is a matter of the will, a quality of the imagination, vigor of the emotions; it is the freshness of the deep spring of life.</p>
<p>Youth means a temperamental predominance of courage over timidity, of the appetite for adventure over the love of ease. This often exits in a man of 60, more than a boy of 20.nobody grows merely by the number of years; we grow old by deserting our ideas. Years may wrinkle the skin, but to give up enthusiasm wrinkles the soul. Worry, fear, self-distrust1 bows the heart and turns the spirit back to dust.</p>
<p>Whether 60 or 16, there is in every human being’s heart the lure of wonders, the unfailing childlike appetite of what’s next and the joy of the game of living. In the center of your heart and my heart there is a wireless station; so long as it receives messages of beauty, hope, cheer, courage and power from men and from infinite, so long as you are young.</p>
<p>When the aerials are down, and your spirit is covered with the snows of cynicism and the ice of pessimism, then you’ve grown old, even at 20, but as long as your aerials are up, to catch waves of optimism, there’s hope you may die young at 80.</p>
<span>点击我查看翻译</span><span style="display:none;">收起</span>
</div>
<div class="drawer-show">
<h4>译文:青春不是年华,而是心境</h4>
<p>青春不是年华,而是心境;青春不是桃面、丹唇、柔膝,而是深沉的意志、宏伟的想象、炽热的感情;青春是生命的深泉在涌。青春气贯长虹,勇锐盖过怯弱,进去压倒苟安,如此锐气,二十后生有之,六旬男子则更多见。年年有加,并非垂老;理想丢弃,方堕暮年。岁月悠悠,衰微只及肌肤;热忱抛却,颓唐必至灵魂。烦忧、惶恐、丧失自信,定使心灵扭曲,意气如灰。</p>
<p>无论年届花甲,抑或二八芳龄,心中皆有生命之欢乐,奇迹之诱惑,孩童般天真久盛不衰。人人心中</p>
</div>
</div>
3. css样式表:
*{
margin:0;
padding:0;
}
p{
line-height:30px;
}
.drawer{
margin:20px auto;
width:800px;
height:auto;
box-shadow:0 0 3px #999;
}
.drawer-content,.drawer-show{
padding:20px;
}
.drawer-content p{
text-indent:2em;
font-size:16px;
}
.drawer-content span{
color:blue;
cursor:pointer;
margin-left:10px;
}
.drawer-show{
display:none;
}
.drawer-show h4{
margin-bottom:18px;
font-size:20px;
text-align:center;
font-weight:500;
}
.drawer-show p{
text-align:left;
text-indent:2em;
}
span{
display:inline-block;
}
4. 原生js代码:
window.onload = function(){
var read = document.querySelectorAll("span");
var drawerShow = document.querySelector(".drawer-show");
read[0].addEventListener("click",show,false);
read[1].addEventListener("click",hide,false);
function show(){
drawerShow.style.display = "block";
read[0].style.display = "none";
read[1].style.display = "block";
}
function hide(){
drawerShow.style.display = "none";
read[0].style.display = "block";
read[1].style.display = "none";
}
}
注:
1.注意区分DOM0级事件处理程序和DOM2级事件处理程序的区别;
关于DOM0级事件处理程序、DOM二级事件处理程序、HTML事件处理程序、IE事件处理程序的区别,请查看:
link(https://blog.youkuaiyun.com/qq_43495629/article/details/87277987).
~如遇错误,欢迎指正;