How to display the Vue H5 project in the center of the layout on the PC side without full-screen stretching

1. Scene reproduction: the layout of the H5 project is stretched on the PC side

insert image description here

2. Code implementation

Write in App.vue, write in mounted for vue2, and write in onMounted for vue3.

Logical explanation:
1. Obtain the terminal type of the current user, and then create a type that stores multiple different H5 terminals.
2. If each element in the H5 terminal array does not belong to the current PC terminal.
3. Then create an iframe inline frame and set the href jump for the iframe frame.
4. Create an iframe style object, and set all the attributes into the iframe style one by one by traversing the attributes of the object.
5. Finally, insert the newly added iframe into document.body.

 			// 以vue2为例
 			mounted(){
    
    
				//为pc则用iframe把移动端页面显示到页面中间
	            let userAgentInfo = navigator.userAgent;
	            let Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
	            //pc
	            if (
	                  !Agents.some(item => userAgentInfo.toLowerCase().includes(item.toLowerCase())) &&
	                  !(self.frameElement && self.frameElement.tagName == "IFRAME")
	            ) {
    
    
	                  let ifrTag = document.createElement("iframe");
	                  document.body.innerHTML = "";
	                  ifrTag.setAttribute("src", location.href);
	                  let styleObj = {
    
    
	                        width: "480px",
	                        height: "920px",
	                        position: "absolute",
	                        left: "50%",
	                        transform: "translateX(-50%)",
	                  };
	                  Object.entries(styleObj).forEach(([key, value]) => {
    
    
	                        ifrTag.style[key] = value;
	                  });
	                  document.body.append(ifrTag);
	            }
			}

After writing and saving, go to the PC to refresh the web page to see the effect.
In fact, React and Angular can also be written, because this code is written in native JS.

3. The final rendering

insert image description here

4. Doubt

Will the original layout of my H5 be affected?
Answer: No, it will not affect H5 at all. The above code is only for PC.

Supongo que te gusta

Origin blog.csdn.net/Steven_Son/article/details/131204295
Recomendado
Clasificación