javascript 要素を拡大させる
- 2021.01.10
- javascript
- javascript

javascriptで、transformのscaleを使用して、要素を拡大させるサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
scale使い方
transformのscaleを使用すると、指定した要素を拡大させることが可能です。
1 2 3 4 5 6 |
document.getElementById("id名").style.transform = "scale(x, y)"; x 水平方向の拡大縮小率 y 垂直方向の拡大縮小率 |
scale使い方
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/* html */ <div id="main" style="width: 200px; padding: 20px; margin-bottom: 10px; border: 1px dashed #333333;"> Hello Javascript!! </div> /* javascript */ 'use strict'; let x = 1; setInterval("hoge()", 100); function hoge(){ x = x + 0.1; document.getElementById("main").style.transform = "scale(" + x + "," + x + ")"; } |
実行結果をみると、指定した要素が拡大されていることが確認できます。

macのsafari(13.1.1)でも同じ結果となります。

また、document.getElementByIdの省略と関数をアロー化して、簡潔に記述することもできます。
1 2 3 4 5 6 7 8 9 |
setInterval("hoge()", 100); const hoge = () => { x = x + 0.1; main.style.transform = "scale(" + x + "," + x + ")"; } |
サンプルコード
以下は、
「拡大」ボタンをクリックすると「要素」を拡大して、
「縮小」ボタンをクリックすると「要素」を縮小させる
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"> </head> <script> let count = 0; const hoge = () => { count--; result.style.transform = "translate(0%," + count + "%)"; } const foo = () => { count++; result.style.transform = "translate(0%," + count + "%)"; } window.onload = () => { up.onclick = () => { hoge() }; down.onclick = () => { foo() }; } </script> <body> <div class="container mx-auto my-56 w-64 px-4"> <div id="sample" class="flex flex-col justify-center"> <p id="result" class="bg-gradient-to-r from-green-400 to-blue-500 text-white py-2 px-4 rounded-full mb-3 mt-4"> 要素</p> <button id="up" class="bg-gradient-to-r from-purple-400 via-pink-500 to-red-500 text-white py-2 px-4 rounded-full mb-3 mt-4">上へ</button> <button id="down" class="bg-gradient-to-r from-purple-400 via-pink-500 to-red-500 text-white py-2 px-4 rounded-full mb-3 mt-4">下へ</button> </div> </div> </body> </html> |
移動していることが確認できます。

-
前の記事
Ruby 配列の行と列を入れ替える 2021.01.10
-
次の記事
php array_filterで配列から空の値を除く 2021.01.10
コメントを書く