[英]Scaling a transformation based on window size
我有一個元素在懸停時使用變換進行縮放。 這很好,但是如果我希望網站可以在各種瀏覽器/屏幕尺寸上查看,那么在 static 數字上縮放它並不是很有用。 代碼現在看起來像這樣:
<!DOCTYPE html>
<html>
<head>
<script>
{
const w = window.innerWidth/200;
const h = window.innerHeight/200;
}
</script>
<style>
.botright
{
width: 100px;
height: 100px;
top: 50%;
left: 50%;
position: absolute;
background: pink;
transition: transform 500ms ease-in-out;
transform-origin: left top;
display: flex;
align-items: center;
justify-content: center;
font-family: sans-serif;
}
.botright:hover
{
transform: scaleX(w) scaleY(h);
font-size: 0;
}
值得注意的位在代碼的頂部和底部(js 和:hover
)。 我無法在 css 的其他任何地方使用在 javascript 中創建的w
或h
常量,並且 js 無法在:hover
內部或包含以下工作相對於視圖 window 的長度和寬度的大小。
如果元素本身被縮放到 window 大小,則scale()
中的 static 數字將起作用,但這會導致一些其他問題,更重要的是,這不是我想要做的。
當前的功能版本確實使用一個簡單的數字來縮放元素,但是因為元素始終是 100px x 100px(我故意使用像素,因為無論如何我都希望元素在不懸停時是正方形),縮放只是做一個更大的正方形。
我正在尋找一種縮放正方形的方法,以便在將鼠標懸停在上面時,它總是 go 正好位於可用 window 空間的最邊緣。
我認為你可以這樣做:
.box { background: #05273D; border-radius: 5px; height: 100px; width: 100px; margin: 100px; transition: transform 1s; }.box:hover { transform: scale(2); }
<div class='box'></div>
您可以從這里了解更多信息: https://www.w3schools.com/css/css3_2dtransforms.asp
您不能將 Javascript 變量傳遞給這樣的style
標簽。 一種解決方案是使用 javascript 創建style
標簽並將計算值連接起來。
<script> const w = window.innerWidth/200; const h = window.innerHeight/200; var styleTag = document.createElement("style"); styleTag.innerHTML = '.botright:hover { transform: scaleX(' + w + ') scaleY(' + h + '); font-size: 0; }'; document.head.appendChild(styleTag); </script> <style>.botright { width: 100px; height: 100px; top: 50%; left: 50%; position: absolute; background: pink; transition: transform 500ms ease-in-out; transform-origin: left top; display: flex; align-items: center; justify-content: center; font-family: sans-serif; } </style> <div class="botright">TEST</div>
但是請注意,這不會在窗口調整大小時更新。 如果需要,可以將 js 代碼放入綁定到 window 調整大小事件的 function 中。 但是,如果您是這樣,您的 function 應該為樣式標簽提供一個 id,如果它存在,則在再次添加之前將其刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.