vue利用a标签点击下载保存图片

vue前端a标签点击下载保存图片

想不调用接口直接下载保存图片,翻csdn把手都翻出血了。

亲测一行代码搞定:

把图片地址设在download属性上,而不是放在href中:

关键代码:

   <a href="" :download="item.src" class="download"></a>
<template>
  <div class="contain">
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="790px" height="554px" :show-close="true" :autoplay="false" :close-on-click-modal="false">
      <el-carousel indicator-position="outside">
        <el-carousel-item v-for="item in imgList" :key="item.id">
          <a href="" :download="item.src" class="download"></a>
          <img :src="item.src" alt="" />
        </el-carousel-item>
      </el-carousel>
    </el-dialog>
  </div>
</template>
<script>
import xiazai from '@/assets/icons/xiazai.svg';

export default {
  name: 'Carousel',
  props: {
    imgList: {
      type: Array,
      default: [],
      required: true,
    },
  },
  data() {
    return {
      downloadImg: [],
      dialogVisible: false,
    };
  },
  methods: {},
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__headerbtn {
  display: none;
}
.download {
  height: 50px;
  width: 50px;
  display: block;
  position: fixed;
  background: url('~@/assets/icons/xiazai.svg') no-repeat;
  font-size: 30px;
  opacity: 0.75;
  line-height: 300px;
  right: 0;
  bottom: 0;
}
::v-deep .el-dialog__header {
  display: flex;
  justify-content: center;
  align-items: center;
}
::v-deep .is-active .el-carousel__button {
  background: #3a86ff;
  border-radius: 4px;
  width: 18px;
  height: 8px;
}
::v-deep .el-carousel__button {
  height: 8px;
  width: 8px;
  border-radius: 8px;
}
::v-deep .el-carousel__indicators--outside {
  padding-top: 20px;
}
</style>

### Vue 中实现禁止长按保存图片 为了实现在 Vue 项目中禁止用户通过长按来保存图片,可以采用 CSS 和 JavaScript 结合的方式。具体来说: #### 使用 CSS 的 `pointer-events` 属性 设置图片的样式为不可交互状态能够有效防止长按操作触发默认行为。 ```css .imgMsg { pointer-events: none; } ``` 这种方式简单直接,但是会使得所有的鼠标或触摸事件都无法作用于该元素[^1]。 如果希望更灵活地控制,在某些情况下允许特定的操作,则需要借助 JavaScript 来处理 touch 事件。 #### 利用 JavaScript 处理 Touch 事件 对于更加复杂的场景,可以在父级容器监听触控事件,根据实际需求决定是否阻止默认动作。 ```javascript // 假设这是在一个 Vue 组件的方法内定义 imgTouchStart(e) { const targetClass = e.target.classList.contains('imgMsg'); if(targetClass){ // 阻止浏览器默认行为(即不允许长按保存) e.preventDefault(); // 清除可能存在的定时器重置计时 clearTimeout(this.touchTimer); this.touchTimer = setTimeout(() => { console.log("Long press detected but prevented."); this.touchTimer = null; }, 500); // 设置合理的长时间阈值 } }, tipEnd() { clearTimeout(this.touchTimer); if (!this.touchTimer) { console.log("Short tap or long press ended without action."); } } ``` 上述代码片段展示了如何在 Vue 方法里捕获触摸开始(`touchstart`)和结束(`touchend`)事件,利用 `preventDefault()` 函数取消默认的行为,从而达到禁用长按保存的效果[^2]。 另外一种做法是在模板中的 img 标签上直接添加 `.native`修饰符绑定原生事件处理器,这同样适用于单个组件内的局部逻辑[^3]。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值