手機端自適應字體大小和元素寬度自適應
阿新 • • 發佈:2018-04-10
type 測試 nim AD ali jquery round 查詢 element
第一種,媒體查詢:
@media (min-width:0px){ html{font-size:12px;} } @media (min-width: 320px){ html{font-size:12px;} } @media (min-width: 340px){ html{font-size:13px;} } @media (min-width: 360px){ html{font-size:14px;} } @media (min-width: 380px){ html{font-size:15px;} } @media (min-width: 400px){ html{font-size:15px;} } @media (min-width: 420px){ html{font-size:16px;} }
第二種:頁面插入js(推薦):
<script type="text/javascript"> function fontSize(){ var deviceWidth=document.documentElement.clientWidth>768?768:document.documentElement.clientWidth; document.documentElement.style.fontSize=(deviceWidth/25)+"px"; } fontSize(); window.onresize=fontSize; </script>
插入一段我自己寫的測試例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" /> <title>自適應字體大小和元素高度</View Codetitle> <style type="text/css"> *{margin: 0;padding: 0;text-align: center;} h1{font-size: 2rem;padding: 2rem;} p{font-size: 1rem;padding: 1px;} div{width: 5rem;height: 4rem;background-color: #f00;} </style> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> function fontSize(){ var deviceWidth=document.documentElement.clientWidth>768?768:document.documentElement.clientWidth; document.documentElement.style.fontSize=(deviceWidth/25)+"px"; } fontSize(); window.onresize=fontSize; </script> </head> <body> <h1>標題</h1> <p>內容</p> <div></div> </body> </html>
手機端自適應字體大小和元素寬度自適應