您的位置:首页 > Web前端 > CSS

原生实现一个toast组件;ul下li点击确定是哪个

2017-09-25 19:07 369 查看
1.简单的一个toast组件

首先贴上代码:

<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.toast-wrap{
position: fixed;
top:0px;
bottom: 0px;
left:0px;
right:0px;
background-color:#363636;
opacity:0.5;
display: none;
z-index: 10;
}
.toast-block{
position: fixed;
width: 30%;
height:150px;
left:35%;
right:35%;
/*这里left相对于span左侧,right是相对于右侧*/
border-radius: 4px;
background-color: #fff;
font-size:25px;
text-align: center;
padding: 4px 2px 4px 2px;
z-index: 999;
animation: move 1s ease;
-webkit-animation: move 1s ease;
animation-fill-mode: forwards;
}
@-webkit-keyframes move
{
from{top: 100%}
to{top: 40%}
}
</style>
</head>
<body>
<p>我是其他内容</p>
<div class="toast-wrap">
<span id="toast-block" onclick="closeToast()"></span>
</div>
<button onclick="toast('I am a toast!')">open</button>
</body>
<script type="text/javascript">
function $(name){
return document.querySelector(name);
}
var wrap = $('.toast-wrap'),block=$('#toast-block');
function toast(word){
wrap.style.display = 'block';
block.className = "toast-block";
block.innerHTML = word;
}
function closeToast(){
wrap.style.display = 'none';
block.className = "";
}
</script>
</html>


核心思路是一个包裹层wrap,一个内部toast,两者的position都设为fixed,通过设定z-index以及wrap的top,right,bottom,left使得包裹层全屏覆盖,然后给toast设定动画,动画改变top。js代码的思路是运行函数就修改
4000
样式,让wrap可见,toast的className修改,立即具有动画效果。关闭函数则是还原样式。

2.ul下li点击确定是哪个;

<style type="text/css">
li{
list-style-type:none;
/*消除li前面的点*/
width:100px;
height: 20px;
background-color: yellow;
margin-top:2px;
}
</style>
</head>
<body>
<ul id="myul">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</body>
<script type="text/javascript">
var ul = document.querySelector('#myul');
//var li = document.querySelector('li');
//以className或在tagName只会选择到第一个节点、
//getElementByTagName(),getElementByClassName()则会返回集合
document.onclick = function(e){
//console.log(e.target);
if(e.target.parentNode==ul){
console.log(e.target.innerText);
alert(e.target.innerText);
//innerHTML 是返回或者添加HTML代码段 innerHTML = '<li>6</li>';
//innerText 返回或者添加内容
}
}

</script>


如果是无序列表ul,可以使用e.target获取到具体哪个li被点击,获取到Node节点,通过innerText获取信息,但是无法得知在ul中的顺序。

如果是有序列表ol,可以使用e.target获取li节点,然后有value属性获取到节点顺序。

另外,网上提出一个childNodes属性,

ul.childNodes.indexOf(e,target);返回li的顺序 ,在ie下可行,在chrome等浏览器childNodes返回的集合不仅有li节点,还包括空格,可以先去除空格再寻找顺序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  css toast ul-li
相关文章推荐