jquery入门

133 阅读1分钟
  $(window).keydown(function (e) {            let top = $('.plane').position().top            let left = $('.plane').position().left            switch (e.keyCode) {                case 87:                    top -= 10                    break                case 83:                    top += 10                    break                case 65:                    left -= 10                    break                case 68:                    left += 10                    break                case 74:                    attack()                    break            }            let maxLeft = $('.container').innerWidth() - $('.plane').innerWidth()            let maxTop = $('.container').innerHeight() - $('.plane').innerHeight()            let result = $.filterLeftAndTop(left, top, maxLeft, maxTop)            $('.plane').css('left', result.left).css('top', result.top)        })        //节流        let endTime = new Date()        function attack() {            if (new Date() - endTime < 500) return console.log('i am buzy');            let bullet = $('<div/>').addClass('bullet')            $('.container').append(bullet)            bullet.css('top', $('.plane').position().top - 10)            bullet.css('left', $('.plane').position().left + $('.plane').innerWidth() / 2 - bullet.innerWidth() / 2)            endTime = new Date()        }        setInterval(() => {            $('.bullet').each(function () {                $(this).css('top', $(this).position().top - 10)                if ($(this).position().top < -20)                    $(this).remove()            })        }, 100)        setInterval(() => {            $('.enemy').each(function() {                $(this).css('top',$(this).position().top + 5)                if($(this).position().top>$('.container').innerHeight())                $(this).remove()            })        },50)        setInterval(()=>{            let enemy = $('<div/>').addClass('enemy')            $('.container').append(enemy)            enemy.css('left',Math.round(Math.random()*($('.container').innerWidth()-enemy.innerWidth())))        },1000)

这里飞机的代码是飞机大战 比较简易   其中使用到了switch语句 这里主要是通过键盘的keycode编码的让switch语句执行 这也是switch 语句的一大优点  代码清晰 选择执行语句  

setInterval(() => {            $('.bullet').each(function () {                $(this).css('top', $(this).position().top - 10)                if ($(this).position().top < -20)                    $(this).remove()            })        }, 100)        setInterval(() => {            $('.enemy').each(function() {                $(this).css('top',$(this).position().top + 5)                if($(this).position().top>$('.container').innerHeight())                $(this).remove()            })        },50)

上面的语句中子弹div 和 敌人div 在移动到界限的时候采取remove 这样就可以减少浏览器的运行压力了