如何使用 CSS 和 JavaScript 繞圓旋轉多個物件?
Dec 07, 2024 am 11:46 AM使用CSS 繞圓旋轉多個物件
在嘗試創建多個物件繞圓旋轉的動畫時,遇到了只有一個物體旋轉正確。本文旨在提供解決此問題的指導,以確保所有所需的物件圍繞圓圈無縫旋轉。
現有程式碼和實作
提供的程式碼涉及「outCircle」充當旋轉中心的div,在其中,巢狀的「旋轉」div 包含要設定動畫的對象。使用 CSS3 動畫,「旋轉」div 配置為圍繞「outCircle」無限旋轉。但是,嘗試在「旋轉」div 中新增其他物件會導致不良行為。
解決方案
要解決此問題,基於JavaScript 的方法更合適用於處理多個物件旋轉:
var radius = 100; // Adjust to place items closer or farther from the center var fields = $('.item'); // Target the objects to be rotated var container = $('#container'); // Parent div encasing the rotating objects var width = container.width(); var height = container.height(); var angle = 0; var step = (2 * Math.PI) / fields.length; // Calculate the angular separation between objects fields.each(function() { // Calculate the coordinates for each object based on its position in the circle var x = Math.round(width / 2 + radius * Math.cos(angle) - $(this).width() / 2); var y = Math.round(height / 2 + radius * Math.sin(angle) - $(this).height() / 2); if (console) { console.log($(this).text(), x, y); // Display coordinates for debugging } $(this).css({ left: x + 'px', // Set the left position top: y + 'px', // Set the top position }); // Increment the angle based on the spacing between objects angle += step; });
登入後複製
附加註意事項
此外,CSS3可用於設定動畫行為:
body { padding: 2em; } #container { width: 200px; height: 200px; margin: 10px auto; border: 1px solid #000; position: relative; border-radius: 50%; animation: spin 10s linear infinite; // Define the animation duration and direction } .item { width: 30px; height: 30px; line-height: 30px; text-align: center; border-radius: 50%; position: absolute; background: #f00; animation: spin 10s linear infinite reverse; // Reverse the animation for each object } @keyframes spin { 100% { transform: rotate(1turn); // Rotate the objects one full turn } }
登入後複製
範例
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>
登入後複製
此方法提供一個靈活且可擴展的解決方案,用於使用CSS3 和JavaScript 繞圓旋轉任意數量的物件。
以上是如何使用 CSS 和 JavaScript 繞圓旋轉多個物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱門文章
兩個點博物館:邦格荒地地點指南
4 週前
By 尊渡假赌尊渡假赌尊渡假赌
擊敗分裂小說需要多長時間?
3 週前
By DDD
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章
兩個點博物館:邦格荒地地點指南
4 週前
By 尊渡假赌尊渡假赌尊渡假赌
擊敗分裂小說需要多長時間?
3 週前
By DDD
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章標籤

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)