jQuery之图片预览
主要知识点:
1)on() 事件绑定
2)DOM操作的实战运用
代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>在线相册</title> <style> ul{ list-style: none; overflow: hidden; } ul li{ display: block; float: left; margin-left: 5px; } ul li img{ display: block; } </style> </head> <body> <h2>在线预览</h2> <p> <label for="img_url">上传图片: <input type="file" name="img_url" id="img_url" placeholder="上传图片"> </label> </p> <p> 图片类型: <input type="radio" id="rect" name="border" value="0"><label for="rect">直角</label> <input type="radio" id="radius" name="border" value="10%"><label for="radius">圆角</label> <input type="radio" id="circle" name="border" value="50%"><label for="circle">圆形</label> </p> <p> 是否添加阴影: <select name="shadow"> <option value="0">不添加</option> <option value="1">添加</option> </select> </p> <p> <button class="btn">添加图片</button> </p> <div> <h3>预览</h3> <ul></ul> </div> </body> <script src="./js/jquery.min.js"></script> <script> $(function(){ $(".btn").on("click",function(){ // 获取图片路径 let imgUrl = $('#img_url').val(); if(imgUrl.length === 0){ alert("请选择一张图片"); $('#img_url').focus(); return false; } console.log('http://theyon.com/0918/images/'+imgUrl.split('\\')[2]); imgUrl = 'http://theyon.com/0918/images/'+imgUrl.split('\\')[2]; // 获取图片显示类型 let imgType = $("input[type=radio]:checked").val(); console.log(imgType); // 获取图片显示效果 let shadow = 'none'; if($(':selected').val() === '1'){ shadow = '3px 3px 3px #666'; } // 创建图片 let img = $('<img>') .attr('src',imgUrl) .width(150) .height(150) .css({ 'border-radius': imgType, 'box-shadow': shadow }); // 图片操作 let before = $('<button></button>').text('前移'); let after = $('<button></button>').text('后移'); let remove = $('<button></button>').text('删除'); // 创建一个<li>用来放所有的内容 let contaier = $('<li>'); //将图片和三个按钮打包到<li>中 contaier.append(img,before,after,remove); $('ul').append(contaier); before.click(function(){ let current = $(this).parent(); let prev = current.prev(); prev.before(current); }); after.click(function(){ let current = $(this).parent(); let next = current.next(); next.after(current); }) remove.click(function(){ let current = $(this).parent(); if(confirm('确认删除吗?')){ current.remove(); } return false; }) }) }) </script> </html>
运行结果