Home >Web Front-end >JS Tutorial >Dynamically load image paths and maintain the relative independence of JavaScript controls_javascript skills

Dynamically load image paths and maintain the relative independence of JavaScript controls_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:20:25972browse

There were three methods considered at the time:
1. Write the path directly in the js file, but if the path level of the reference page changes, there will be no solution.
2. Write a class and put it in the css file in the theme package or create a separate css file specifically for the date control. However, there is no need to use classes for other elements in the control. Creating corresponding CSS documents separately seems to be a big deal.
3. After excluding the above two methods, it is natural to use the method of dynamically loading the image path.
The key code is as follows:

Copy code The code is as follows:

//Create a global Variable saving path
var imgRootUrl = "";

//Get the directory where the image path is located
var strPath=window.document.location.pathname; //Get the directory part after the host address
var thisUrlCount = strPath.split('/');
var hierarchyOfFolders = thisUrlCount.length-2;//Get the directory hierarchy
for(iRoot=0;iRoot{
imgRootUrl ="../";
}
imgRootUrl ="Images/"; //This Images can actually be set as a parameter. Since the naming of all project image folders is fixed, there is no parameter set, but Still save scalability.

After adding the image, the control effect is quite beautiful:
Dynamically load image paths and maintain the relative independence of JavaScript controls_javascript skills
By the way, attach all the properties of window.document.location:
document.location.hash // The part after # VS window.location.hash
document.location.host // Domain name port number
document.location.hostname // Domain name
document.location.href // Full URL
document.location.pathname // Directory part (application)
document.location.port // Port number
document.location.protocol // Network protocol (http:)
document.location. search // The part after ?
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn