|
|

楼主 |
发表于 2022-7-8 12:16
|
显示全部楼层
代码:
- <style>
- #papa {
- margin: auto;
- width: 720px;
- height: 560px;
- box-shadow: 4px 4px 24px #000;
- position: relative;
- }
- #txtbox {
- position: absolute;
- right: 50px;
- top: 50px;
- cursor: pointer;
- }
- .piece {
- position: absolute;
- font: normal 35px / 40px sans-serif; /* 重要 : JS参考行高值,修改时需同步修改 lineHeight 变量 */
- text-shadow: 1px 1px 2px rgba(0,0,0,.8);
- user-select: none;
- transition: all 1.2s;
- }
- </style>
- <div id="papa">
- <div id="txtbox"></div>
- </div>
- <script>
- let txt = '君问归期未有期,巴山夜雨涨秋池。何当共剪西窗烛,却话巴山夜雨时。';
- let num = (min, max) => Math.floor(Math.random() * (max-min+1)) + min;
- breakup(txt,txtbox);
- let pieces = document.querySelectorAll('.piece');
- txtbox.onmousemove = () => pieces.forEach((ele) => ele.style.transform = 'rotate(0deg) translate(0px,0px)');
- txtbox.onmouseout = () => pieces.forEach((ele) => ele.style.transform = `rotate(${num(-180,180)}deg) translate(${num(-20,20)}px,${num(-20,20)}px)`);
- function breakup(text,ele) {
- let txtAr = text.split('');
- let lineChars = 8, lineHeight = 40; //lineChars : 每行字数,liengHeight : 行高(依据CSS设定的行高)
- ele.style.width = lineChars * lineHeight + 'px';
- ele.style.height = Math.ceil(txtAr.length / lineChars) * lineHeight + 'px';
- txtAr.forEach((e,k) => {
- let span = document.createElement('span');
- span.className = 'piece';
- span.style.transform = `rotate(${num(-180,180)}deg) translate(${num(-30,30)}px,${num(-30,30)}px)`;
- span.style.color = `rgb(${num(0,255)},${num(0,255)},${num(0,255)})`;
- span.innerText = e;
- span.style.left = (k % lineChars) * lineHeight + 'px';
- span.style.top = Math.floor(k / lineChars) * lineHeight + 'px';
- ele.appendChild(span);
- });
- }
- </script>
复制代码
|
|