13

前端笔记(使用html\css\jquery造n*n的格子,根据预算购买到最多的商品)

 4 years ago
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.
neoserver,ios ssh client

需求:创建一个n*n的格子,n是输入框的数字,点击重渲染可以重新画一个n*n的格子,鼠标移入格子中,对应的格子背景设变成红色,点击对应的格子,背景色变成蓝色,再点一次还原颜色。

VZ3EziJ.png!web

要造格子有好几种方式,可以用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()
}

需求:根据所有的商品单价(元),和你的预算(元),指定一个尽可能买得多的商品的方案

iQBRv2y.png!web

思路是 先将所有商品的价格按从小到大排序起来,设置这个预算值初始为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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK