利用css變數實現按鈕懸浮效果

VitoLI發表於2018-10-25

轉自 www.zcfy.cc/article/stu…

css


<style>
        .button{
            position: relative;
            appearance: none;
            background: #f72359;
            padding: 1em 2em;
            border: none;
            color: white;
            font-size: 1.2em;
            cursor: pointer;
            outline: none;
            overflow: hidden;
            border-radius: 100px;
        }
        .button > span {
            position: relative;
        }

        .button::before {
             --size: 0;

             content: '';
             position: absolute;
             left: var(--x);
             top: var(--y);
             width: var(--size);
             height: var(--size);
             background: radial-gradient(circle closest-side, #4405f7, transparent);
             transform: translate(-50%, -50%);
             transition: width .2s ease, height .2s ease;
         }

        .button:hover::before {
             --size: 400px;
         }
    </style>
複製程式碼

HTML

<button class="button"><span>hover on me</span></button>
複製程式碼

javascript


<script>
    document.querySelector('.button').addEventListener('mousemove', function (e) {
        var x = e.pageX - e.target.offsetLeft
        var y = e.pageY - e.target.offsetTop
        e.target.style.setProperty('--x', `${ x }px`)
        e.target.style.setProperty('--y', `${ y }px`)
    })
</script>

複製程式碼

效果 codepen.io/lilong7676/…

相關文章