SVG或HTML文件中JS代码提示 Uncaught TypeError: Cannot read properties of null (reading ‘setAttribute‘)

本文讲述了在SVG或HTML中使用JS代码时遇到的错误,即提前访问未加载完成的DOM元素。给出了两种解决方案:一是将JS代码放入window.onload事件处理函数中,二是确保JS代码在所有DOM元素加载后执行。

现象

在SVG文件或HTML文件中进行JS代码开发的时候,会碰到这种情况:明明在SVG文件中已经创建了某个对象,但JS代码中通过Id获取该对象,并对该对象的属性进行设置的时候会提示错误(该错误可以在浏览器中按F12—console/控制台 查看)。

const path = document.getElementById('pathcurve');
let d = 'M' + xData_curve[0] + ',' + yData_curve[0]; 
path.setAttribute('d', d); 

原因分析

这是因为在SVG或HTML文件中执行JS代码的时候,DOM元素还未完全加载,此时就在JS代码中试图访问它,就会出现这个问题。

解决方案

1、可以尝试将JS代码放到Windows.onload事件处理函数中进行处理,如代码所示

window.onload = function() {
  let path = document.getElementById('pathcurve');
  if (path ) {
    path .setAttribute('d', 'd');
  } else {
    console.error('Element with id "path " not found');
  }
}

2、简单的方法,就是将JS代码放到整个SVG或HTML文件的底部,确保上方的DOM元素都加载完成再执行JS代码。注意,后期通过SVG或HTML编辑软件增加元素的时候,元素会默认放在文件的底部,注意调整JS代码的顺序。

### 确保地图加载完成并在mounted钩子中绘制绿色丝滑箭头路线 在前端框架(如Vue2)中实现地图加载完成后绘制绿色丝滑箭头路线,并标记起点和终点,同时解决`Uncaught TypeError: Cannot read properties of null (reading 'style')`错误,需要遵循以下方法。 #### 1. 地图初始化与加载完成 确保地图在`mounted`生命周期内加载完成。通过监听地图的`tilesloaded`事件[^1],可以确认地图完全加载后再进行其他操作。 ```javascript methods: { initMap() { const center = new qq.maps.LatLng(39.9042, 116.4074); // 设置地图中心点 this.map = new qq.maps.Map(document.getElementById("container"), { center: center, zoom: 12, }); // 确保地图加载完成 qq.maps.event.addListenerOnce(this.map, "tilesloaded", () => { this.drawTrajectory(); this.addMarkers(); }); }, }, ``` #### 2. 标记起点和终点 通过`Marker`对象分别在起点和终点添加标记。设置不同的图标样式以区分起点和终点。 ```javascript methods: { addMarkers() { const startIcon = "https://example.com/start-icon.png"; const endIcon = "https://example.com/end-icon.png"; const startPoint = new qq.maps.LatLng( this.trajectory[0].lat, this.trajectory[0].lng ); const endPoint = new qq.maps.LatLng( this.trajectory[this.trajectory.length - 1].lat, this.trajectory[this.trajectory.length - 1].lng ); new qq.maps.Marker({ position: startPoint, map: this.map, icon: startIcon, title: "起点", }); new qq.maps.Marker({ position: endPoint, map: this.map, icon: endIcon, title: "终点", }); }, }, ``` #### 3. 绘制带箭头的绿色轨迹 通过`Polyline`对象绘制轨迹,并使用自定义样式实现绿色轨迹和箭头效果。腾讯地图支持通过SVG路径定义箭头样式[^2]。 ```javascript methods: { drawTrajectory() { if (this.polyline) { this.polyline.setMap(null); } const polylineOptions = { path: this.trajectory.map((point) => new qq.maps.LatLng(point.lat, point.lng) ), strokeColor: "#3CB371", // 绿色 strokeWeight: 5, icons: [ { icon: { path: "M 0,-1 0,1 L 3,0 Z", // 自定义箭头SVG路径 fillColor: "#3CB371", fillOpacity: 1, scale: 2, anchor: new qq.maps.Point(15, 15), }, repeat: "50px", // 每隔50像素重复一次箭头 }, ], map: this.map, }; this.polyline = new qq.maps.Polyline(polylineOptions); }, }, ``` #### 4. 解决TypeError错误 为避免`Uncaught TypeError: Cannot read properties of null (reading 'style')`错误,需在触发相关事件前进行判断处理。例如,在重置页面大小时触发事件时,应检查元素是否存在。 ```javascript mounted() { window.addEventListener("resize", () => { if (document.getElementById("container")) { this.initMap(); // 确保地图容器存在时重新初始化地图 } }); }, ``` #### 完整代码示例 将上述功能整合到一个Vue组件中: ```javascript <template> <div> <div id="container" style="width: 100%; height: 500px;"></div> </div> </template> <script> export default { data() { return { map: null, polyline: null, trajectory: [ { lat: 39.9042, lng: 116.4074 }, { lat: 39.9142, lng: 116.4174 }, { lat: 39.9242, lng: 116.4274 }, // 添加更多轨迹点... ], }; }, mounted() { this.initMap(); window.addEventListener("resize", () => { if (document.getElementById("container")) { this.initMap(); // 确保地图容器存在时重新初始化地图 } }); }, methods: { initMap() { const center = new qq.maps.LatLng(39.9042, 116.4074); this.map = new qq.maps.Map(document.getElementById("container"), { center: center, zoom: 12, }); qq.maps.event.addListenerOnce(this.map, "tilesloaded", () => { this.drawTrajectory(); this.addMarkers(); }); }, drawTrajectory() { if (this.polyline) { this.polyline.setMap(null); } const polylineOptions = { path: this.trajectory.map((point) => new qq.maps.LatLng(point.lat, point.lng) ), strokeColor: "#3CB371", strokeWeight: 5, icons: [ { icon: { path: "M 0,-1 0,1 L 3,0 Z", fillColor: "#3CB371", fillOpacity: 1, scale: 2, anchor: new qq.maps.Point(15, 15), }, repeat: "50px", }, ], map: this.map, }; this.polyline = new qq.maps.Polyline(polylineOptions); }, addMarkers() { const startIcon = "https://example.com/start-icon.png"; const endIcon = "https://example.com/end-icon.png"; const startPoint = new qq.maps.LatLng( this.trajectory[0].lat, this.trajectory[0].lng ); const endPoint = new qq.maps.LatLng( this.trajectory[this.trajectory.length - 1].lat, this.trajectory[this.trajectory.length - 1].lng ); new qq.maps.Marker({ position: startPoint, map: this.map, icon: startIcon, title: "起点", }); new qq.maps.Marker({ position: endPoint, map: this.map, icon: endIcon, title: "终点", }); }, }, }; </script> ``` ### 注意事项 - 确保腾讯地图API的Key已正确配置[^1]。 - 轨迹数据需提前准备,可从后端接口获取手动录入。 - 箭头样式可通过调整SVG路径实现不同效果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值