初衷:不少人在初学前端的时候都会问,“如何入门前端?”
同为在前端学习道路上,奋力追赶的一员,本人对于目前网络上所能看到的 “入门级” 的教材并不太满意。学习一门新知识,实例是尤为重要的。在这里本人整理了目前页面上常见功能实现的具体实例。愿能为你们提供一些帮助。
但愿可以与你们互相分享,共同进步。html
效果预览前端
<!-- 触发按钮 --> <button id="triggerBtn">模态框</button> <!-- 模态框 --> <div id="myModal" class="modal"> <div class="modal-content"> <div class="modal-header"> <h2>头部</h2> <span id="closeBtn" class="close">×</span> </div> <div class="modal-body"> <p>这是一个模态框!</p> <p>喜欢就点个赞吧!</p> </div> <div class="modal-footer"> <h3>尾部</h3> </div> </div> </div>
模态框样式git
/*模态框*/ .modal { display: none; /* 默认隐藏 */ position: fixed; /* 根据浏览器定位 */ z-index: 1; /* 放在顶部 */ left: 0; top: 0; width: 100%; /* 全宽 */ height: 100%; /* 全高 */ overflow: auto; /* 容许滚动 */ background-color: rgba(0,0,0,0.4); /* 背景色 */ }
模态框内容样式github
/*模态框内容*/ .modal-content { display: flex; /*采用flexbox布局*/ flex-direction: column; /*垂直排列*/ position: relative; background-color: #fefefe; margin: 15% auto; /*距顶部15% 水平居中*/ padding: 20px; border: 1px solid #888; width: 80%; animation: topDown 0.4s; /*自定义动画,从模态框内容上到下出现*/ } @keyframes topDown { from {top: -300px; opacity: 0} to {top: 0; opacity: 1} } /*模态框头部*/ .modal-header { display: flex; /*采用flexbox布局*/ flex-direction: row; /*水平布局*/ align-items: center; /*内容垂直居中*/ justify-content: space-between; } /*关闭X 样式*/ .close { color: #aaa; float: right; font-size: 28px; font-weight: bold; } .close:hover { color: black; text-decoration: none; cursor: pointer; }
扩展阅读: CSS3 animation 属性web
隔离全局浏览器
(function() { })();
把JS代码放到一个单独的自调用匿名函数中。网络
扩展阅读:深刻理解(function() {})();ide
创建模态框对象函数
/*创建模态框对象*/ var modalBox = {}; /*获取模态框*/ modalBox.modal = document.getElementById("myModal"); /*得到trigger按钮*/ modalBox.triggerBtn = document.getElementById("triggerBtn"); /*得到关闭按钮*/ modalBox.closeBtn = document.getElementById("closeBtn"); /*模态框显示*/ modalBox.show = function() { console.log(this.modal); this.modal.style.display = "block"; } /*模态框关闭*/ modalBox.close = function() { this.modal.style.display = "none"; } /*当用户点击模态框内容以外的区域,模态框也会关闭*/ modalBox.outsideClick = function() { var modal = this.modal; window.onclick = function(event) { if(event.target == modal) { modal.style.display = "none"; } } } /*模态框初始化*/ modalBox.init = function() { var that = this; this.triggerBtn.onclick = function() { that.show(); } this.closeBtn.onclick = function() { that.close(); } this.outsideClick(); }
调用模态框
modalBox.init();
好啦,如今咱们已经写完。
怎么样,是否是很简单。赶快打开浏览器看看吧!
在这里,只是给你们提供一种思路,参考。
具体的实现,每一个人均可以有不一样的方法。
请你们赶快发挥想象,把你最想实现的功能,在电脑敲出来吧!