前端笔记(使用html\css\jquery造n*n的格子,根据预算购买到最多的商品)
source link: http://www.cnblogs.com/wuhairui/p/12678696.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
需求:创建一个n*n的格子,n是输入框的数字,点击重渲染可以重新画一个n*n的格子,鼠标移入格子中,对应的格子背景设变成红色,点击对应的格子,背景色变成蓝色,再点一次还原颜色。
要造格子有好几种方式,可以用table、ul和li,或者直接使用完全的div
这里为了方便理解,我使用ul和li。
定义html:
box用于渲染格子
<div class="box"></div> <div> <input type="text" value="10" id="num"> <input type="button" onclick="render()" value="重渲染"> </div>
css:
这里我们使用ul加flex,让li平分,list-style-type:none;去除li的默认点,li:hover定义鼠标移入时的样式,定义.blue作为样式渲染
.div{ height: 100%; } .box ul{ display: flex; margin: 0; } .box ul li{ width: 10px; height: 10px; border: 1px solid #000; list-style-type:none; } li:hover{ background-color: red; } li.blue{ background-color: blue; }
js:
ul与li的创建使用数组的join转字符串
{ function render(){ let num=$("#num").val()//定几*几格子 let ul=[],li=[] for(let i=0;i<num;i++){ li.push(`<li></li>`) } li=li.join("")//li的dom for(let i=0;i<num;i++){ ul.push(`<ul>${li}</ul>`) } ul=ul.join("")//ul的dom $(".box").html(ul) $("li").click(function(){//点击格子 let isBlue=$(this).hasClass("blue") if(isBlue){ $(this).removeClass("blue") }else{ $(this).addClass("blue") } }) } render() }
需求:根据所有的商品单价(元),和你的预算(元),指定一个尽可能买得多的商品的方案
思路是 先将所有商品的价格按从小到大排序起来,设置这个预算值初始为0,从最便宜的开始买,每买一个就加上当前的价格,直到超出预算,那超出前的那次就是最好的购买方式。
html:
<div> 预算:<input type="text" id="ys" value="200"><br> 商品价格:<input type="text" id="jg" value="50 30 40 55 242 21"><br> <input type="button" value="计算" onclick="js()"><br> 结果:<span id="res"></span> </div>
js:
使用sort进行数值排序,使用split将字符串拆分成数组,使用join将数组转化为字符串
{ function js(){ let ys=$("#ys").val(),jg=$("#jg").val() let res=0,km=[]//需要金额 可买 let arr=jg.split(" ") arr.sort((a,b)=>a-b) for(let i=0;i<arr.length;i++){ res+=Number(arr[i]) console.log(res) if(res > Number(ys)){ res-=Number(arr[i]) break } km.push(Number(arr[i])) } console.log(res,km) $("#res").text(`需要金额:${res},可买物品:${km.join(" ")}`) } }
Recommend
-
39
一个小格子,一天500万!“跳一跳”广告凭啥卖这么贵?
-
59
2018年初,当“微信之父”张小龙在微信公开课上表示,微信内部从来没有说过“情怀”,也没有说过要克制欲望时,业内便猜测微信的商业化或将提速。果不其然,2个月后微信便正式推出了跳一跳广告。互联网行业有这样一句话:当一个线上服务是免费时,你就不
-
31
今天是500余万程序员的节日。 但似乎 对于大多数互联网人来说,这只是个平凡的周三。是的,你看不到任何属于节日应该有的狂欢和热闹,如同节日的主人一样性格低调。他们过节的方式只是相互之间的抱团调侃:...
-
71
-
78
记录与时代并存的技术人,二叉树短视频第六季——《斜杠青年》激情回归。本季二叉树视频,带你走进一群真实的技术人,撕下标签,看看程序员代码之...
-
26
程序员 - @hHarvey -
-
34
[TOC] 最近,需要做这个功能,然后找到一个非常好的论文[1],把代码实现了一下,基本算是解决问题了。论文自己搜一下吧,我也放了一份在[CSDN下载]里面。 基本原理 1.先找出多边形的边界,同时设置这些...
-
5
宝贝格子创始人张天天:跨境电商在直播加持下,已经开始向人带货转变 “如果说2016年是直播元年,那2020年是跨境直播电商的元年,跨境电商从传统的货带人,在直...
-
8
取格子游戏的构造性策略 作者: 张志强 , 发表...
-
1
1.开发环境 JDK版本:17.0.3 IDEA版本: 20...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK