vue 图片选点 定位

<div style="padding: 20px;">
    <div class="case_img" @mousedown="show_coords">
        <img  alt="" style="width: 100%;"
             :src="formState.highlightimg.indexOf('http') > -1
                   ? formState.highlightimg
                   : getBaseImgUrl(formState.highlightimg)"
             >
        <h5 v-for="(itme, i) in formState.dataList" :key="itme.id"
            @click="onEditClick(itme,'edit')"
            @mousedown.stop
            :style="{
                    left: get_100(itme.leftpx),
                    top: get_100(itme.toppx)
                    }">
            {{ i + 1 }}</h5>
    </div>
</div>


// 设置百分比
const  get_100 = (val:any) => {
  // 如果 val 是字符串,且以百分号结尾
  if (typeof val === 'string' && val.endsWith('%')) {
    // 去掉百分号并转换为数字
    return val; // 直接返回原始百分比
  }
  // 如果 val 是数字,转换为百分比
  if (typeof val === 'number') {
    return  ((val / 10000) * 100).toFixed(2) + '%' ;
  }
  // 如果输入的 val 既不是数字也不是以百分号结尾的字符串,返回空字符串或者处理错误
  return '';
}
const show_coords = (e: any) => {
  // 获取当前点击元素(假设它是图片)
  const obj = e.target;
  // 获取当前点击场景的上间距
  const rect = obj.getBoundingClientRect();
  const mt = rect.top + window.scrollY;  // 图片顶部的偏移量(包含页面滚动)
  // 获取当前点击场景的左间距
  const ml = rect.left + window.scrollX;  // 图片左侧的偏移量(包含页面滚动)
  // 获取当前点击场景的宽度
  const mainWidth = rect.width;
  // 获取当前点击场景的高度
  const mainHeight = rect.height;
  // 计算出当前点击位置距离所在场景的左间隔(百分比)
  const x = ((e.clientX - ml) / mainWidth * 100).toFixed(2) + "%";
  // 计算出当前点击位置距离所在场景的上间隔(百分比)
  const y = ((e.clientY - mt) / mainHeight * 100).toFixed(2) + "%";
  // 创建新的参数并加入到数据列表
  let parameter = {
    id: generateRandomId(),
    title: '',
    imgurl: '',
    info: '',
    leftpx: x,   // 使用 x 作为 leftpx
    toppx: y,    // 使用 y 作为 toppx
  };
  // 将新参数加入到数据列表
  console.log('parameter',parameter);
  onEditClick(parameter,'add');
};
// 唯一id
function generateRandomId() {
  const timestamp = new Date().getTime(); // 获取当前时间戳
  const randomNum = Math.floor(Math.random() * 1000); // 生成一个0-999之间的随机数
  return `id_${timestamp}_${randomNum}`; // 返回拼接后的ID字符串
}

posted @ 2025-03-04 11:23  前端搬运工bug  阅读(85)  评论(0)    收藏  举报