者:錢魏Way
來源:https://www.biaodianfu.com/python-datetime.html
Python的時間處理模塊在日常的使用中用的較多多,但是使用的時候基本上都是要查資料,還是有些麻煩的,梳理下,便于以后方便的使用。
秒 在1967年的第13屆國際度量衡會議上決定以原子時定義的秒作為時間的國際標準單位:銫133原子基態的兩個超精細能階間躍遷對應輻射的9,192,631,770個周期的持續時間, 起始歷元定在1958年1月1日0時。
原子鐘是一種時鐘,它以原子共振頻率標準來計算及保持時間的準確。原子鐘是世界上已知最準確的時間測量和頻率標準。
GMT 格林威治標準時間(Greenwich Mean Time),是指位于倫敦郊區的皇家格林威治天文臺的標準時間,因為本初子午線(Prime meridian)被定義為通過那里的經線。GMT也叫世界時UT。
UTC 協調世界時間(Coordinated Universal Time), 又稱世界標準時間,基于國際原子鐘,誤差為每日數納秒。協調世界時的秒長與原子時的秒長一致,在時刻上則要求盡量與世界時接近(規定二者的差值保持在 0.9秒以內)。
閏秒 不只有閏年,還有閏秒。閏秒是指為保持協調世界時接近于世界時時刻,由國際計量局統一規定在年底或年中(也可能在季末)對協調世界時增加或減少1秒的調整。由于地球自轉的不均勻性和長期變慢性(主要由潮汐摩擦引起的),會使世界時(民用時)和原子時之間相差超過到±0.9秒時,就把世界時向前撥1秒(負閏秒,最后一分鐘為59秒)或向后撥1秒(正閏秒,最后一分鐘為61秒); 閏秒一般加在公歷年末或公歷六月末。
時區 是地球上的區域使用同一個時間定義。有關國際會議決定將地球表面按經線從南到北,劃分成24個時區,并且規定相鄰區域的時間相差1小時。當人們跨過一個區域,就將自己的時鐘校正1小時(向西減1小時,向東加1小時),跨過幾個區域就加或減幾小時。比如我大中國處于東八區,表示為GMT+8。
夏令時 (Daylight Saving Time:DST),又稱日光節約時制、日光節約時間或夏令時間。這是一種為節約能源而人為規定地方時間的制度,在夏天的時候,白天的時間會比較長,所以為了節約用電,因此在夏天的時候某些地區會將他們的時間定早一小時,也就是說,原本時區是8點好了,但是因為夏天太陽比較早出現,因此把時間向前挪,在原本8點的時候,訂定為該天的9點(時間提早一小時)~如此一來,我們就可以利用陽光照明,省去了花費電力的時間,因此才會稱之為夏季節約時間!
Unix時間戳 指的是從協調世界時(UTC)1970年1月1日0時0分0秒開始到現在的總秒數,不考慮閏秒。
在 Python 文檔里,time是歸類在Generic Operating System Services中,換句話說, 它提供的功能是更加接近于操作系統層面的。通讀文檔可知,time 模塊是圍繞著 Unix Timestamp 進行的。
該模塊主要包括一個類 struct_time,另外其他幾個函數及相關常量。 需要注意的是在該模塊中的大多數函數是調用了所在平臺C library的同名函數, 所以要特別注意有些函數是平臺相關的,可能會在不同的平臺有不同的效果。另外一點是,由于是基于Unix Timestamp,所以其所能表述的日期范圍被限定在 1970 – 2038 之間,如果你寫的代碼需要處理在前面所述范圍之外的日期,那可能需要考慮使用datetime模塊更好。
獲取當前時間和轉化時間格式
>>> import time
>>> time.time()
1473386416.954
>>> time.ctime()
'Fri Sep 09 10:00:25 2016'
>>> time.ctime(time.time())
'Fri Sep 09 10:28:08 2016'
>>> time.asctime()
'Fri Sep 09 10:22:40 2016'
>>> time.asctime(time.localtime())
'Fri Sep 09 10:33:00 2016'
>>> time.localtime()
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=10, tm_min=1, tm_sec=19, tm_wday=4, tm_yday=253, tm_isdst=0)
>>> time.localtime(time.time())
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=10, tm_min=19, tm_sec=11, tm_wday=4, tm_yday=253, tm_isdst=0)
>>> time.gmtime()
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=2, tm_min=13, tm_sec=10, tm_wday=4, tm_yday=253, tm_isdst=0)
>>> time.gmtime(time.time())
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=2, tm_min=15, tm_sec=35, tm_wday=4, tm_yday=253, tm_isdst=0)
struct_time共有9個元素,其中前面6個為年月日時分秒,后面三個分別代表的含義為:
time.mktime()
將一個以struct_time格式轉換為時間戳
>>> time.mktime(time.localtime())
1473388585.0
time.strftime(format[,t]) 把一個struct_time時間轉化為格式化的時間字符串。如果t未指定,將傳入time.localtime()。如果元組中任何一個元素越界,ValueError的錯誤將會被拋出。
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
'2016-09-09 10:54:21'
time.strptime(string[,format])
把一個格式化時間字符串轉化為struct_time。實際上它和strftime()是逆操作。
>>> time.strptime(time.ctime())
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=11, tm_min=0, tm_sec=4, tm_wday=4, tm_yday=253, tm_isdst=-1)
time.sleep(secs)
線程推遲指定的時間運行。單位為秒。
time.clock()
這個需要注意,在不同的系統上含義不同。在UNIX系統上,它返回的是“進程時間”,它是用秒表示的浮點數(時間戳)。而在WINDOWS中,第一次調用,返回的是進程運行的實際時間。而第二次之后的調用是自第一次調用以后到現在的運行時間。(實際上是以WIN32上QueryPerformanceCounter()為基礎,它比毫秒表示更為精確)
import time
time.sleep(1)
print("clock1:%s" % time.clock())
time.sleep(1)
print("clock2:%s" % time.clock())
time.sleep(1)
print("clock3:%s" % time.clock())
運行結果為:
clock1:1.57895443216e-06
clock2:1.00064381867
clock3:2.00158724394
其中第一個clock()輸出的是程序運行時間,第二、三個clock()輸出的都是與第一個clock的時間間隔
import time
print(time.timezone)
print(time.tzname)
print(time.tzname[0].decode("GBK"))
print(time.tzname[1].decode("GBK"))
運行結果
-28800
('\xd6\xd0\xb9\xfa\xb1\xea\xd7\xbc\xca\xb1\xbc\xe4', '\xd6\xd0\xb9\xfa\xcf\xc4\xc1\xee\xca\xb1')
中國標準時間
中國夏令時
datetime 比 time 高級了不少,可以理解為 datetime 基于 time 進行了封裝,提供了更多實用的函數。
datetime模塊定義了下面這幾個類:
注:上面這些類型的對象都是不可變(immutable)的。
date類定義了一些常用的類方法與類屬性:
from datetime import date
import time
print('date.max:', date.max)
print('date.min:', date.min)
print('date.resolution:', date.resolution)
print('date.today():', date.today())
print('date.fromtimestamp():', date.fromtimestamp(time.time()))
執行結果:
date.max: 9999-12-31
date.min: 0001-01-01
date.resolution: 1 day, 0:00:00
date.today(): 2016-09-12
date.fromtimestamp(): 2016-09-12
date提供的實例方法和屬性:
from datetime import date
today=date.today()
print('today:', today)
print('.year:', today.year)
print('.month:', today.month)
print('.replace():', today.replace(year=2017) )
print('.weekday():', today.weekday())
print('.isoweekday():', today.isoweekday())
print('.isocalendar():', today.isocalendar())
print('.isoformat():', today.isoformat())
print('.strftime():', today.strftime('%Y-%m-%d') )
print('.toordinal():', today.toordinal())
執行結果:
today: 2016-09-12
.year: 2016
.month: 9
.replace(): 2017-09-12
.weekday(): 0
.isoweekday(): 1
.isocalendar(): (2016, 37, 1)
.isoformat(): 2016-09-12
.strftime(): 2016-09-12
.toordinal(): 736219
date還對某些操作進行了重載,它允許我們對日期進行如下一些操作:
time類的構造函數如下:(其中參數tzinfo,它表示時區信息。)
class datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]])
time類定義的類屬性:
time類提供的實例方法和屬性:
像date一樣,也可以對兩個time對象進行比較,或者相減返回一個時間間隔對象。這里就不提供例子了。
datetime是date與time的結合體,包括date與time的所有信息。它的構造函數如下:datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]),各參數的含義與date、time的構造函數中的一樣,要注意參數值的范圍。
datetime類定義的類屬性與方法:
from datetime import datetime
import time
print('datetime.max:', datetime.max)
print('datetime.min:', datetime.min)
print('datetime.resolution:', datetime.resolution)
print('today():', datetime.today())
print('now():', datetime.now())
print('utcnow():', datetime.utcnow())
print('fromtimestamp(tmstmp):', datetime.fromtimestamp(time.time()))
print('utcfromtimestamp(tmstmp):', datetime.utcfromtimestamp(time.time()))
運行結果:
datetime.max: 9999-12-31 23:59:59.999999
datetime.min: 0001-01-01 00:00:00
datetime.resolution: 0:00:00.000001
today(): 2016-09-12 19:57:00.761000
now(): 2016-09-12 19:57:00.761000
utcnow(): 2016-09-12 11:57:00.761000
fromtimestamp(tmstmp): 2016-09-12 19:57:00.761000
utcfromtimestamp(tmstmp): 2016-09-12 11:57:00.761000
datetime類提供的實例方法與屬性(很多屬性或方法在date和time中已經出現過,在此有類似的意義,這里只羅列這些方法名,具體含義不再逐個展開介紹,可以參考上文對date與time類的講解。):
year、month、day、hour、minute、second、microsecond、tzinfo:
像date一樣,也可以對兩個datetime對象進行比較,或者相減返回一個時間間隔對象,或者日期時間加上一個間隔返回一個新的日期時間對象。
通過timedelta函數返回一個timedelta對象,也就是一個表示時間間隔的對象。函數參數情況如下所示:
class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
其沒有必填參數,簡單控制的話第一個整數就是多少天的間隔的意思:
datetime.timedelta(10)
兩個時間間隔對象可以彼此之間相加或相減,返回的仍是一個時間間隔對象。而更方便的是一個datetime對象如果減去一個時間間隔對象,那么返回的對應減去之后的datetime對象,然后兩個datetime對象如果相減返回的是一個時間間隔對象。這很是方便。
tzinfo是一個抽象類,不能被直接實例化。需要派生子類,提供相應的標準方法。datetime模塊并不提供tzinfo的任何子類。最簡單的方式是使用pytz模塊。
pytz是Python的一個時區處理模塊(同時也包括夏令時),在理解時區處理模塊之前,需要先要了解一些時區的概念。
要知道時區之間的轉換關系,其實這很簡單:把當地時間減去當地時區,剩下的就是格林威治時間了。例如北京時間的18:00就是18:00+08:00,相減以后就是10:00+00:00,因此就是格林威治時間的10:00。
Python的datetime可以處理2種類型的時間,分別為offset-naive和offset-aware。前者是指沒有包含時區信息的時間,后者是指包含時區信息的時間,只有同類型的時間才能進行減法運算和比較。
datetime模塊的函數在默認情況下都只生成offset-naive類型的datetime對象,例如now()、utcnow()、fromtimestamp()、utcfromtimestamp()和strftime()。其中now()和fromtimestamp()可以接受一個tzinfo對象來生成offset-aware類型的datetime對象,但是標準庫并不提供任何已實現的tzinfo類,只能自己實現。
下面就是實現格林威治時間和北京時間的tzinfo類的例子:
ZERO_TIME_DELTA=timedelta(0)
LOCAL_TIME_DELTA=timedelta(hours=8) # 本地時區偏差
class UTC(tzinfo):
def utcoffset(self, dt):
return ZERO_TIME_DELTA
def dst(self, dt):
return ZERO_TIME_DELTA
class LocalTimezone(tzinfo):
def utcoffset(self, dt):
return LOCAL_TIME_DELTA
def dst(self, dt):
return ZERO_TIME_DELTA
def tzname(self, dt):
return '+08:00'
一個tzinfo類需要實現utcoffset、dst和tzname這3個方法。其中utcoffset需要返回夏時令的時差調整;tzname需要返回時區名,如果你不需要用到的話,也可以不實現。
一旦生成了一個offset-aware類型的datetime對象,我們就能調用它的astimezone()方法,生成其他時區的時間(會根據時差來計算)。而如果拿到的是offset-naive類型的datetime對象,也是可以調用它的replace()方法來替換tzinfo的,只不過這種替換不會根據時差來調整其他時間屬性。因此,如果拿到一個格林威治時間的offset-naive類型的datetime對象,直接調用replace(tzinfo=UTC())即可轉換成offset-aware類型,然后再調用astimezone()生成其他時區的datetime對象。
看上去一切都很簡單,但不知道你還是否記得上文所述的夏時令。提起夏時令這個玩意,真是讓我頭疼,因為它沒有規則可循:有的國家實行夏時令,有的國家不實行,有的國家只在部分地區實行夏時令,有的地區只在某些年實行夏時令,每個地區實行夏時令的起止時間都不一定相同,而且有的地方TMD還不是用幾月幾日來指定夏時令的起止時間的,而是用某月的第幾個星期幾這種形式。
pytz模塊,使用Olson TZ Database解決了跨平臺的時區計算一致性問題,解決了夏令時帶來的計算問題。由于國家和地區可以自己選擇時區以及是否使用夏令時,所以pytz模塊在有需要的情況下得更新自己的時區以及夏令時相關的信息。
pytz提供了全部的timezone信息,如:
import pytz
print(len(pytz.all_timezones))
print(len(pytz.common_timezones))
運行結果:
588
436
如果需要獲取某個國家的時區,可以使用如下方式:
import pytz
print(pytz.country_timezones('cn'))
執行結果:
[u'Asia/Shanghai', u'Asia/Urumqi']
中國一個有兩個時區,一個為上海,一個為烏魯木齊,我們來看下我們有什么區別:
from datetime import datetime
import pytz
print(pytz.country_timezones('cn'))
tz1=pytz.timezone(pytz.country_timezones('cn')[0])
print(tz1)
print(datetime.now(tz1))
tz2=pytz.timezone(pytz.country_timezones('cn')[1])
print(tz2)
print(datetime.now(tz2))
執行結果:
[u'Asia/Shanghai', u'Asia/Urumqi']
Asia/Shanghai
2016-09-14 09:55:39.384000+08:00
Asia/Urumqi
2016-09-14 07:55:39.385000+06:00
可以看到上海是東八區,而烏魯木齊是東六區。
操作起來有而比較簡單,本地時區與UTC的互轉:
from datetime import datetime
import pytz
now=datetime.now()
tz=pytz.timezone('Asia/Shanghai')
print(tz.localize(now))
print(pytz.utc.normalize(tz.localize(now)))
執行結果:
2016-09-14 10:25:44.633000+08:00
2016-09-14 02:25:44.633000+00:00
使用astimezone()可以進行時區與時區之間的轉換。
from datetime import datetime
import pytz
utc=pytz.utc
beijing_time=pytz.timezone('Asia/Shanghai')
japan_time=pytz.timezone('Asia/Tokyo')
now=datetime.now(beijing_time)
print("Beijing Time:",now)
print("UTC:",now.astimezone(utc))
print("JAPAN TIME:",now.astimezone(japan_time))
執行結果:
Beijing Time: 2016-09-14 10:19:22.671000+08:00
UTC: 2016-09-14 02:19:22.671000+00:00
JAPAN TIME: 2016-09-14 11:19:22.671000+09:00
另外可以采用 replace來修改時區,時區多出6分鐘(不要使用)。具體原因為:
民國17年(1928年),國民政府統一中國,原中央觀象臺的業務由南京政府中央研究院的天文研究所和氣象研究所分別接收。天文研究所編寫的曆書基本上沿襲中央觀象臺的做法,仍將全國劃分為5個標準時區,只是在有關交氣、合朔、太陽出沒時刻等處,不再使用北平的地方平時,而改以南京所在的標準時區的區時即東經120°標準時替代。從北平地方平時改為東經120°標準時,兩者相差了352秒。
from datetime import datetime
import pytz
now=datetime.now()
print(now)
tz=pytz.timezone('Asia/Shanghai')
print(now.replace(tzinfo=tz))
執行結果:
2016-09-14 10:29:20.200000
2016-09-14 10:29:20.200000+08:06
由于用到的場景比較少,不做細化學習。
安裝模塊:pip install Python-dateutil
解析時間到datetime格式,支持大部分時間字符串。沒指定時間默認是0點,沒指定日期默認是今天,沒指定年份默認是今年。
from dateutil import parser
print(parser.parse("8th March,2004"))
print(parser.parse("8 March,2004"))
print(parser.parse("March 8th,2004"))
print(parser.parse("March 8,2004"))
print(parser.parse("2016-09-14"))
print(parser.parse("20160914"))
print(parser.parse("2016/09/14"))
print(parser.parse("09/14/2016"))
print(parser.parse("09,14"))
print(parser.parse("12:00:00"))
print(parser.parse("Wed, Nov 12"))
執行結果:
2004-03-08 00:00:00
2004-03-08 00:00:00
2004-03-08 00:00:00
2004-03-08 00:00:00
2016-09-14 00:00:00
2016-09-14 00:00:00
2016-09-14 00:00:00
2016-09-14 00:00:00
2016-09-09 00:00:00
2016-09-14 12:00:00
2016-11-12 00:00:00
函數主要功能:按照規則生成日期和時間。函數原型如下。
rrule(self, freq, dtstart=None, interval=1, wkst=None, count=None, until=None, bysetpos=None, bymonth=None, bymonthday=None, byyearday=None, byeaster=None, byweekno=None, byweekday=None, byhour=None, byminute=None, bysecond=None, cache=False)
其中:
更多參考:http://dateutil.readthedocs.io/en/stable/index.html
Arrow 提供了一個友好而且非常易懂的方法,用于創建時間、計算時間、格式化時間,還可以對時間做轉化、提取、兼容 python datetime 類型。它包括dateutil模塊,根據其文檔描述Arrow旨在“幫助你使用更少的代碼來處理日期和時間”。
使用utcnow()功能創建 UTC 時間。
使用to()方法,我們將 UTC 時間轉換為本地時間。
import arrow
utc=arrow.utcnow()
print(utc)
print(utc.to('local'))
本地時間是特定區域或時區中的時間。
import arrow
now=arrow.now()
print(now)
print(now.to('UTC'))
使用now()功能創建本地時間。 to()方法用于將本地時間轉換為 UTC 時間。
get()方法用于解析時間。
import arrow
d1=arrow.get('2012-06-05 16:20:03', 'YYYY-MM-DD HH:mm:ss')
print(d1)
d2=arrow.get(1504384602)
print(d2)
該示例從日期和時間字符串以及時間戳解析時間。
import arrow
utc=arrow.utcnow()
print(utc)
unix_time=utc.timestamp
print(unix_time)
date=arrow.Arrow.fromtimestamp(unix_time)
print(date)
該示例顯示本地時間和 Unix 時間。 然后,它將 Unix 時間轉換回 date 對象。
使用fromtimestamp()方法,我們將 Unix 時間轉換回 Arrow 日期對象。
也可以將日期格式化為 Unix 時間。
import arrow
utc=arrow.utcnow()
print(utc.format('X'))
通過將’X’說明符傳遞給format()方法,我們將當前本地日期打印為 Unix 時間。
日期和時間可以用format()方法格式化。
import arrow
now=arrow.now()
year=now.format('YYYY')
print("Year: {0}".format(year))
date=now.format('YYYY-MM-DD')
print("Date: {0}".format(date))
date_time=now.format('YYYY-MM-DD HH:mm:ss')
print("Date and time: {0}".format(date_time))
date_time_zone=now.format('YYYY-MM-DD HH:mm:ss ZZ')
print("Date and time and zone: {0}".format(date_time_zone))
格式說明:
import arrow
utc=arrow.utcnow()
print(utc.to('US/Pacific').format('HH:mm:ss'))
print(utc.to('Europe/Bratislava').format('HH:mm:ss'))
print(utc.to('Europe/Moscow').format('HH:mm:ss'))
可以使用weekday()或format()方法找到日期的工作日。
import arrow
d1=arrow.get('1948-12-13')
print(d1.weekday())
print(d1.format('dddd'))
shift()方法用于移動時間。
import arrow
now=arrow.now()
print(now.shift(hours=5).time())
print(now.shift(days=5).date())
print(now.shift(years=-8).date())
import arrow
now=arrow.now()
print(now.format("YYYY-MM-DD HH:mm:ss ZZ"))
print(now.dst())
該示例使用dst()顯示夏令時。
在社交網站上,我們經常可以看到諸如“一個小時前”或“ 5 分鐘前”之類的術語,這些術語可以為人們提供有關帖子創建或修改時間的快速信息。 Arrow 包含humanize()方法來創建此類術語。
import arrow
now=arrow.now()
d1=now.shift(minutes=-15).humanize()
print(d1)
d2=now.shift(hours=5).humanize()
print(d2)
國際標準ISO 8601,是國際標準化組織的日期和時間的表示方法,全稱為《數據存儲和交換形式·信息交換·日期和時間的表示方法》,在API接口開發中涉及的比較多。
>>> import dateutil.parser
>>> dateutil.parser.parse('2008-09-03T20:56:35.450686Z') # RFC 3339 format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())
>>> dateutil.parser.parse('2008-09-03T20:56:35.450686') # ISO 8601 extended format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.parse('20080903T205635.450686') # ISO 8601 basic format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.parse('20080903') # ISO 8601 basic format, date only
datetime.datetime(2008, 9, 3, 0, 0)
或者使用如下方式解析:
>>> datetime.datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")
另外還可以使用iso8601模塊:http://pyiso8601.readthedocs.io/en/latest/
其他日期與時間工具:
如果你覺得有幫助,請 點贊 + 關注 一下,支持博主發布更多好文章!
始時間time,結束時間timeEnd.
console.time() console.timeEnd()
把自己要測試的代碼置于兩個函數之間,比如:
結果:
給參數的時候,就是自定義標識符:
此時不再是default:
就這么多了。
歡迎關注。
現代網頁設計中,動畫和過渡是提升用戶體驗的重要手段。通過使用 CSS,我們可以在不影響頁面性能的前提下,實現平滑和吸引人的視覺效果。本文將介紹 CSS 動畫和過渡的基礎知識,并通過幾個例子展示如何在你的網站中應用它們。
CSS 過渡允許你在 CSS 屬性值之間創建平滑的動畫效果。當一個元素的屬性值改變時,過渡效果會在一定時間內平滑地過渡到新的屬性值。
transition: property duration timing-function delay;
img:hover {
transform: scale(1.2);
transition: transform 0.3s ease-in-out;
}
這個例子中,當鼠標懸停在圖片上時,圖片會在0.3秒內放大到原來的1.2倍大小,過渡效果為ease-in-out。
CSS 動畫提供了更強大的控制,允許你創建復雜的動畫序列,通過定義關鍵幀(keyframes)來控制動畫的中間狀態。
@keyframes animation-name {
from {
/* 初始狀態 */
}
to {
/* 結束狀態 */
}
}
或者使用百分比來定義多個關鍵幀:
@keyframes animation-name {
0% { /* 初始狀態 */ }
50% { /* 中間狀態 */ }
100% { /* 結束狀態 */ }
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.icon-spin {
animation: spin 2s linear infinite;
}
這個例子創建了一個名為spin的動畫,使得圖標無限期地旋轉。
接下來,我們將通過幾個實戰例子來展示 CSS 動畫和過渡的具體應用。
.button {
position: relative;
overflow: hidden;
transition: background-color 0.3s;
}
.button:after {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 5px;
height: 5px;
background: rgba(255, 255, 255, 0.7);
opacity: 0;
border-radius: 100%;
transform: scale(1, 1) translate(-50%);
transform-origin: 50% 50%;
}
.button:active:after {
width: 300px;
height: 300px;
opacity: 1;
transition: width 0.5s, height 0.5s, opacity 0s 0.5s;
}
在這個例子中,當按鈕被點擊時,會產生一個波紋效果,模擬水波紋擴散。
.fade-in {
animation: fadeIn 1s ease-in-out;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.fade-out {
animation: fadeOut 1s ease-in-out;
}
@keyframes fadeOut {
from { opacity: 1; }
to { opacity: 0; }
}
這個例子中定義了兩個動畫,一個用于元素的淡入,另一個用于元素的淡出。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Animation and Transition Example</title>
<style>
body {
font-family: 'Arial', sans-serif;
margin: 0;
padding: 0;
background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
background-size: 400% 400%;
animation: gradientBG 15s ease infinite;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
min-height: 100vh;
}
@keyframes gradientBG {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
.logo {
font-size: 2em;
color: #007bff;
margin-bottom: 20px;
animation: spin 3s linear infinite;
}
.scrolling-text {
margin: 20px 0;
background-color: #333;
color: #fff;
padding: 10px;
white-space: nowrap;
overflow: hidden;
position: relative;
}
.scrolling-text p {
position: absolute;
width: 100%;
height: 100%;
margin: 0;
line-height: 50px;
text-align: center;
/* Starting position */
transform: translateX(100%);
/* Apply animation to this element */
animation: scroll-text 10s linear infinite;
}
@keyframes scroll-text {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
.interactive-card {
background-color: #fff;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
padding: 20px;
margin: 20px;
border-radius: 10px;
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.interactive-card:hover {
transform: translateY(-10px);
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}
.color-block {
width: 100px;
height: 100px;
background-color: #17a2b8;
margin: 20px;
border-radius: 50%;
transition: background-color 0.5s ease, transform 0.5s ease;
}
.color-block:hover {
background-color: #28a745;
transform: rotate(180deg);
}
</style>
</head>
<body>
<div class="logo">
<i class="fas fa-sync-alt"></i> Animated Logo
</div>
<div class="scrolling-text">
<p>This text scrolls infinitely. Pay attention to how it moves smoothly from right to left.</p>
</div>
<div class="interactive-card">
<h3>Interactive Card</h3>
<p>Hover over this card to see it move. It's a simple yet effective way to add interactivity to your design.</p>
</div>
<div class="color-block"></div>
</body>
</html>
CSS 動畫和過渡是前端開發者的強大工具,它們可以在不犧牲性能的情況下為用戶提供流暢、引人注目的界面交互。通過掌握這些技術,你可以創造出更加動態和生動的網頁體驗。記住,動畫應該用來增強用戶體驗,而不是分散用戶的注意力,適量而恰當地使用動畫效果是關鍵。
*請認真填寫需求信息,我們會在24小時內與您取得聯系。