最近菜鸟公司要做一个这样的功能,后端返回一个合同的整体html,前端进行签字,以下是一些重要思路!
注:本文章是给自己看的,读者酌情考虑!
script 代码
let bigBoxHeight = ref(0); // 获取到元素 let bigBox = document.querySelector(".bigBox"); // 设置高度为 auto bigBox.style.height = "auto"; // 获取 offsetHeight --》 真实高度 const height = bigBox.offsetHeight; // 设置值 bigBoxHeight.value = height; template 代码
感谢:原生js获取元素transform的scale和rotate
// 获取设置了transform的元素 let contractBox = document.querySelector(".contractBox"); // 获取浏览器计算后的结果 let st = window.getComputedStyle(contractBox, null); // 从结算后的结果中找到 transform,也可以直接 st.transform var tr = st.getPropertyValue("transform"); if (tr === "none") { // 为none表示未设置 bigBox.style.height = "auto"; const height = bigBox.offsetHeight + 50; bigBoxHeight.value = height; } else { bigBox.style.height = "auto"; // 缩放需要 * 缩放比例 + 边距(margin/padding) const height = bigBox.offsetHeight * 0.5 + 50; bigBoxHeight.value = height; } getComputedStyle 可以学习我的博客:看 Javascript实战详解 收获一
上面设置transform是因为返回的html文档不是那么的自适应,所以菜鸟就在手机端,让其渲染700px,但是再缩小0.5倍去展示,即可解决!
css 代码
@media screen and (max-width: 690px) { .contractBox { width: 700px !important; transform: scale(0.5); // 防止延中心点缩放而导致上面留白很多(合同很长,7000px左右) transform-origin: 5% 0; } } .bigBox { position: relative; // 设置是因为 scale 缩放了但是元素还是占本身那么大,所以要超出隐藏 overflow: hidden; .markBox { width: 100%; position: absolute; left: 0; bottom: 0; top: 0; bottom: 0; } } .contractBox { width: 70%; margin: 50px auto 0px; overflow: hidden; } 这里设置 5% 是为了居中,因为这里有个问题就是不能设置bigBox为display:flex,不然里面的内容就是按照width:100%然后缩放0.5,而不是width:700px来缩放的!
是flex搞的鬼,菜鸟这里就用了个简单办法。
其实正统做法应该是获取宽度,再用窗口宽度减去获取的宽度 / 2,然后通过该值设置margin!
菜鸟既然想到了上面的居中方式,那就直接实现了,这里给上代码!
script 代码
// 是否缩放,来确定margin-left取值 let isScale = ref(false); let bigBoxmargin = ref(0); let bigBox = document.querySelector(".bigBox"); let contractBox = document.querySelector(".contractBox"); let st = window.getComputedStyle(contractBox, null); var tr = st.getPropertyValue("transform"); if (tr === "none") { isScale.value = false; bigBox.style.height = "auto"; const height = bigBox.offsetHeight + 50; bigBoxHeight.value = height; } else { isScale.value = true; bigBox.style.height = "auto"; const height = bigBox.offsetHeight * 0.5 + 50; // 不用 st.witdh 是因为 st.witdh 获取的值是 700px,不能直接运算,这里菜鸟就偷懒了,不想处理了 bigBoxmargin.value = (window.innerWidth - 700 * 0.5) / 2; bigBoxHeight.value = height; } template 代码
这里签字效果,菜鸟是使用 el-dialog 实现的,el-dialog 的使用方式见:element plus 使用细节
这里主要粘贴签字的代码
保存 清除 关闭 因为这里的 client 设置的偏移量都是 0,菜鸟不会改(感觉应该加上el-dialog的头部+边框的偏移量),如果不取消的话,就是错位着写的!
这里禁止是因为手机端,签名时写 “竖” 操作时,容易触发下拉整个界面的事件!导致写字中断,体验感极差,所以弹窗弹出时阻止事件,关闭后移除!
这里函数 preventDefault 必须提出,不然会取消不掉!
获取元素必须在 onMounted 中,但是 el-dialog 即使写在 onMounted 里面也不行,需要加上 nextTick !