찾다
웹 프론트엔드HTML 튜토리얼css3-手把手 transform 小时钟_html/css_WEB-ITnose

学习css3ing,正在学习transfomr,突发奇想用此做个小时钟,开始吧:

  1. 准备前期工作,把时钟的表盘,时分秒针,实时时间标签 的大概样子做好,效果如图:

html代码如下:

<div class="main"> <div id="timeLabel"></div> <div id="hour"></div> <div id="minute"></div> <div id="second"></div> </div>

css 代码如下:

 1  <style>  2  * {  3  margin: 0;  4  padding: 0;  5 }  6  .main {  7  position: relative;  8  margin: 100px auto;  9  width: 300px; 10  height: 300px; 11  border-radius: 300px; 12  border: 1px solid #000; 13  box-shadow:2px 5px; 14 } 15  #timeLabel { 16  position: absolute; 17  background-color:pink; 18  width:100px; 19  height:30px; 20  left:100px; 21  top:180px; 22 } 23 24  #hour { 25  width: 100px; 26  height: 10px; 27  background-color: red; 28  position:absolute; 29  left:150px; 30  top:145px; 31 } 32  #minute { 33  width:120px; 34  height:8px; 35  background-color:blue; 36  position:absolute; 37  left:150px; 38  top:146px; 39 } 40  #second { 41  width: 140px; 42  height: 4px; 43  background-color: green; 44  position: absolute; 45  left: 150px; 46  top: 148px; 47 } 48  </style>

  2. 初始化默认时间,和表盘刻度 ,效果如下:

更改后的css代码:

 <style>        * {            margin: 0;            padding: 0;        }        .main {            position: relative;            margin: 100px auto;            width: 300px;            height: 300px;            border-radius: 300px;            border: 1px solid #000;            box-shadow: 2px 5px #808080;        }        #timeLabel {            position: absolute;            background-color: pink;            width: 80px;            height: 25px;            left: 110px;            top: 180px;            color: #fff;            line-height: 25px;            text-align: center;        }        #hour {            width: 100px;            height: 10px;            background-color: red;            position: absolute;            left: 150px;            top: 145px;            transform-origin: 0 50%;        }        #minute {            width: 120px;            height: 8px;            background-color: blue;            position: absolute;            left: 150px;            top: 146px;            transform-origin: 0 50%;        }        #second {            width: 140px;            height: 4px;            background-color: green;            position: absolute;            left: 150px;            top: 148px;            transform-origin: 0 50%;        }        .hourPointer, .minuterPointer, .secondPointer {            position: absolute;            transform-origin: 0 50%;        }        .hourPointer {            height: 10px;            width: 12px;            left: 150px;            top: 145px;            background-color: #f00;            z-index:3;        }        .minuterPointer {            height: 8px;            width: 10px;            left: 150px;            top: 146px;            background-color: #b6ff00;            z-index: 2;        }        .secondPointer {            height: 6px;            width: 8px;            left: 150px;            top: 147px;            background-color: #fa8;            z-index: 1;        }    </style>

初始化 js代码:

window.onload = function () {            initClock();                  }        var timer = null;        function $(id) {            return document.getElementById(id)        }        function CreateKeDu(pElement, className, deg, translateWidth) {            var Pointer = document.createElement("div");            Pointer.className = className            Pointer.style.transform = "rotate(" + deg + "deg)   translate(" + translateWidth + "px)";            pElement.appendChild(Pointer);        }        function initClock() {            var main = $("biaopan");            var timeLabel = $("timeLabel");            var hour = $("hour");            var minute = $("minute");            var second = $("second");            var now = new Date();            var nowHour = now.getHours();            var nowMinute = now.getMinutes();            var nowSecond = now.getSeconds();            //初始化timeLabel            timeLabel.innerHTML = nowHour + ":" + nowMinute + ":" + nowSecond;            //初始化表盘            for (var index = 0; index < 4; index++) {                CreateKeDu(main, "hourPointer", index * 90, 138);            }            for (var index = 0; index < 12; index++) {                CreateKeDu(main, "minuterPointer",index*30, 140);            }            for (var index = 0; index < 60; index++) {                CreateKeDu(main, "secondPointer", index * 6, 142);            }            //初始化时分秒针            second.style.transform = "rotate(" + (nowSecond * 6 - 90) + "deg)";            minute.style.transform = "rotate(" + (nowMinute * 6 + 1 / 10 * nowSecond - 90) + "deg)";            hour.style.transform = "rotate(" + (nowHour * 30 + 1 / 2 * nowMinute + 1 / 120 * nowSecond - 90) + "deg)";        }

3.添加定时器:

js代码如下:

 //定时器        function startMove() {            clearInterval(timer);            timer = setInterval(function () {                var now = new Date();                var nowSecond = now.getSeconds();                var nowMinute = now.getMinutes();                var nowHour = now.getHours();                second.style.transform = "rotate(" + (nowSecond * 6 - 90) + "deg)";                minute.style.transform = "rotate(" + (nowMinute * 6 + 1 / 10 * nowSecond - 90) + "deg)";                hour.style.transform = "rotate(" + (nowHour * 30 + 1 / 2 * nowMinute + 1 / 120 * nowSecond - 90) + "deg)";                timeLabel.innerHTML = nowHour + ":" + nowMinute + ":" + nowSecond;            }, 1000);        }

  4.使用OOP方式更改:

修改后的js代码如下:

function Clock() {            //定义属性            this.main = this.$("biaopan");            this.timeLabel = this.$("timeLabel");            this.hour = this.$("hour");            this.minute = this.$("minute");            this.second = this.$("second");            this.nowHour = null;            this.nowMinute = null;            this.nowSecond = null;            this.timer = null;            var _this = this;            //初始化函数            var init = function () {                _this.getNowTime();                _this.initClock();                _this.InterVal();            }            init();        }        Clock.prototype.$ = function (id) {            return document.getElementById(id)        }        Clock.prototype.CreateKeDu = function (className, deg, translateWidth) {            var Pointer = document.createElement("div");            Pointer.className = className            Pointer.style.transform = "rotate(" + deg + "deg)   translate(" + translateWidth + "px)";            this.main.appendChild(Pointer);        }        Clock.prototype.getNowTime = function () {            var now = new Date();            this.nowHour = now.getHours();            this.nowMinute = now.getMinutes();            this.nowSecond = now.getSeconds();        }        Clock.prototype.setPosition = function () {            this.second.style.transform = "rotate(" + (this.nowSecond * 6 - 90) + "deg)";            this.minute.style.transform = "rotate(" + (this.nowMinute * 6 + 1 / 10 * this.nowSecond - 90) + "deg)";            this.hour.style.transform = "rotate(" + (this.nowHour * 30 + 1 / 2 * this.nowMinute + 1 / 120 * this.nowSecond - 90) + "deg)";        }        Clock.prototype.initClock = function () {            //初始化timeLabel            this.timeLabel.innerHTML = this.nowHour + ":" + this.nowMinute + ":" + this.nowSecond;            //初始化表盘            for (var index = 0; index < 4; index++) {                this.CreateKeDu("hourPointer", index * 90, 138);            }            for (var index = 0; index < 12; index++) {                this.CreateKeDu("minuterPointer", index * 30, 140);            }            for (var index = 0; index < 60; index++) {                this.CreateKeDu("secondPointer", index * 6, 142);            }            this.setPosition();        }        Clock.prototype.InterVal = function () {            clearInterval(this.timer);            var _this = this;            this.timer = setInterval(function () {                _this.getNowTime();                _this.second.style.transform = "rotate(" + (_this.nowSecond * 6 - 90) + "deg)";                _this.minute.style.transform = "rotate(" + (_this.nowMinute * 6 + 1 / 10 * _this.nowSecond - 90) + "deg)";                _this.hour.style.transform = "rotate(" + (_this.nowHour * 30 + 1 / 2 * _this.nowMinute + 1 / 120 * _this.nowSecond - 90) + "deg)";                _this.timeLabel.innerHTML = _this.nowHour + ":" + _this.nowMinute + ":" + _this.nowSecond;            }, 1000);        }

  

最后调用如下:

window.onload = function () {            new Clock();        }

最终页面代码:

                <script>        function Clock() {            //定义属性            this.main = this.$(&quot;biaopan&quot;);            this.timeLabel = this.$(&quot;timeLabel&quot;);            this.hour = this.$(&quot;hour&quot;);            this.minute = this.$(&quot;minute&quot;);            this.second = this.$(&quot;second&quot;);            this.nowHour = null;            this.nowMinute = null;            this.nowSecond = null;            this.timer = null;            var _this = this;            //初始化函数            var init = function () {                _this.getNowTime();                _this.initClock();                _this.InterVal();            }            init();        }        Clock.prototype.$ = function (id) {            return document.getElementById(id)        }        Clock.prototype.CreateKeDu = function (className, deg, translateWidth) {            var Pointer = document.createElement(&quot;div&quot;);            Pointer.className = className            Pointer.style.transform = &quot;rotate(&quot; + deg + &quot;deg)   translate(&quot; + translateWidth + &quot;px)&quot;;            this.main.appendChild(Pointer);        }        Clock.prototype.getNowTime = function () {            var now = new Date();            this.nowHour = now.getHours();            this.nowMinute = now.getMinutes();            this.nowSecond = now.getSeconds();        }        Clock.prototype.setPosition = function () {            this.second.style.transform = &quot;rotate(&quot; + (this.nowSecond * 6 - 90) + &quot;deg)&quot;;            this.minute.style.transform = &quot;rotate(&quot; + (this.nowMinute * 6 + 1 / 10 * this.nowSecond - 90) + &quot;deg)&quot;;            this.hour.style.transform = &quot;rotate(&quot; + (this.nowHour * 30 + 1 / 2 * this.nowMinute + 1 / 120 * this.nowSecond - 90) + &quot;deg)&quot;;        }        Clock.prototype.initClock = function () {            //初始化timeLabel            this.timeLabel.innerHTML = this.nowHour + &quot;:&quot; + this.nowMinute + &quot;:&quot; + this.nowSecond;            //初始化表盘            for (var index = 0; index &lt; 4; index++) {                this.CreateKeDu(&quot;hourPointer&quot;, index * 90, 138);            }            for (var index = 0; index &lt; 12; index++) {                this.CreateKeDu(&quot;minuterPointer&quot;, index * 30, 140);            }            for (var index = 0; index &lt; 60; index++) {                this.CreateKeDu(&quot;secondPointer&quot;, index * 6, 142);            }            this.setPosition();        }        Clock.prototype.InterVal = function () {            clearInterval(this.timer);            var _this = this;            this.timer = setInterval(function () {                _this.getNowTime();                _this.second.style.transform = &quot;rotate(&quot; + (_this.nowSecond * 6 - 90) + &quot;deg)&quot;;                _this.minute.style.transform = &quot;rotate(&quot; + (_this.nowMinute * 6 + 1 / 10 * _this.nowSecond - 90) + &quot;deg)&quot;;                _this.hour.style.transform = &quot;rotate(&quot; + (_this.nowHour * 30 + 1 / 2 * _this.nowMinute + 1 / 120 * _this.nowSecond - 90) + &quot;deg)&quot;;                _this.timeLabel.innerHTML = _this.nowHour + &quot;:&quot; + _this.nowMinute + &quot;:&quot; + _this.nowSecond;            }, 1000);        }        window.onload = function () {            new Clock();        }    </script>    


 总结:本例中使用了css3 的transform属性中的 rotate的旋转效果和translate的位移效果,关于transform的使用 请参考  http://www.w3school.com.cn/cssref/pr_transform.asp

 

 

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
텍스트에서 웹 사이트로 : HTML의 힘텍스트에서 웹 사이트로 : HTML의 힘Apr 13, 2025 am 12:07 AM

HTML은 웹 페이지를 작성하는 데 사용되는 언어로, 태그 및 속성을 통해 웹 페이지 구조 및 컨텐츠를 정의합니다. 1) HTML과 같은 태그를 통해 문서 구조를 구성합니다. 2) 브라우저는 HTML을 구문 분석하여 DOM을 빌드하고 웹 페이지를 렌더링합니다. 3) 멀티미디어 기능을 향상시키는 HTML5의 새로운 기능. 4) 일반적인 오류에는 탈수 된 레이블과 인용되지 않은 속성 값이 포함됩니다. 5) 최적화 제안에는 시맨틱 태그 사용 및 파일 크기 감소가 포함됩니다.

HTML, CSS 및 JavaScript 이해 : 초보자 안내서HTML, CSS 및 JavaScript 이해 : 초보자 안내서Apr 12, 2025 am 12:02 AM

WebDevelopmentReliesonHtml, CSS 및 JavaScript : 1) HtmlStructuresContent, 2) CSSSTYLESIT, 및 3) JAVASCRIPTADDSINGINTERACTIVITY, BASISOFMODERNWEBEXPERIENCES를 형성합니다.

HTML의 역할 : 웹 컨텐츠 구조HTML의 역할 : 웹 컨텐츠 구조Apr 11, 2025 am 12:12 AM

HTML의 역할은 태그 및 속성을 통해 웹 페이지의 구조와 내용을 정의하는 것입니다. 1. HTML은 읽기 쉽고 이해하기 쉽게하는 태그를 통해 컨텐츠를 구성합니다. 2. 접근성 및 SEO와 같은 시맨틱 태그 등을 사용하십시오. 3. HTML 코드를 최적화하면 웹 페이지로드 속도 및 사용자 경험이 향상 될 수 있습니다.

HTML 및 코드 : 용어를 자세히 살펴 봅니다HTML 및 코드 : 용어를 자세히 살펴 봅니다Apr 10, 2025 am 09:28 AM

"Code"는 "Code"BroadlyIncludeLugageslikeJavaScriptandPyThonforFunctureS (htMlisAspecificTypeofCodeFocudecturecturingWebContent)

HTML, CSS 및 JavaScript : 웹 개발자를위한 필수 도구HTML, CSS 및 JavaScript : 웹 개발자를위한 필수 도구Apr 09, 2025 am 12:12 AM

HTML, CSS 및 JavaScript는 웹 개발의 세 가지 기둥입니다. 1. HTML은 웹 페이지 구조를 정의하고 등과 같은 태그를 사용합니다. 2. CSS는 색상, 글꼴 크기 등과 같은 선택기 및 속성을 사용하여 웹 페이지 스타일을 제어합니다.

HTML, CSS 및 JavaScript의 역할 : 핵심 책임HTML, CSS 및 JavaScript의 역할 : 핵심 책임Apr 08, 2025 pm 07:05 PM

HTML은 웹 구조를 정의하고 CSS는 스타일과 레이아웃을 담당하며 JavaScript는 동적 상호 작용을 제공합니다. 세 사람은 웹 개발에서 의무를 수행하고 화려한 웹 사이트를 공동으로 구축합니다.

HTML은 초보자를 위해 쉽게 배우나요?HTML은 초보자를 위해 쉽게 배우나요?Apr 07, 2025 am 12:11 AM

HTML은 간단하고 배우기 쉽고 결과를 빠르게 볼 수 있기 때문에 초보자에게 적합합니다. 1) HTML의 학습 곡선은 매끄럽고 시작하기 쉽습니다. 2) 기본 태그를 마스터하여 웹 페이지를 만들기 시작하십시오. 3) 유연성이 높고 CSS 및 JavaScript와 함께 사용할 수 있습니다. 4) 풍부한 학습 리소스와 현대 도구는 학습 과정을 지원합니다.

HTML의 시작 태그의 예는 무엇입니까?HTML의 시작 태그의 예는 무엇입니까?Apr 06, 2025 am 12:04 AM

anexampleStartingtaginhtmlis, whithbeginsaparagraph.startingtagsareessentialinhtmlastheyinitiate rements, definetheirtypes, andarecrucialforstructurituringwebpages 및 smanstlingthedom.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.