current position:Home>Class object oriented programming idea

Class object oriented programming idea

2022-06-24 09:51:25Time202051

<main>
    <div id="app" style="width: 200px; height: 200px; background:#E34334">houdunren.com</div>
</main>
<script>
    class Ad {
    
        constructor(options) {
    
            this.$el = document.querySelector(options.el)
            this.$options = Object.assign({
     timeout: 2, step: 1 }, options)
            // Initial movement direction ,1 Down / towards the right  -1  Up / towards the left 
            this.x = this.y = 1

            //  Set positioning mode 
            this.$el.style.position = 'fixed'
            setInterval(this.run.bind(this), this.$options.timeout)
        }
        // Timing callback function 
        run() {
    
            this.$el.style.left = this.left() + 'px'
            this.$el.style.top = this.top() + 'px'
        }
        left() {
    
            let {
     x, width } = this.$el.getBoundingClientRect()
            let {
     clientWidth } = document.documentElement
            if (x > clientWidth - width) this.x = -1
            if (x < 0) this.x = 1

            return x + this.x * this.$options.step
        }
        top() {
    
            let {
     y, height } = this.$el.getBoundingClientRect()
            let {
     clientHeight } = document.documentElement
            if (y > clientHeight - height) this.y = -1
            if (y < 0) this.y = 1

            return y + this.y * this.$options.step
        }
    }

    new Ad({
     el: '#app', timeout: 10, step: 1 })
</script>

copyright notice
author[Time202051],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/175/202206240903258858.html

Random recommended