1. 程式人生 > 實用技巧 >uniapp vue v-html,顯示富文字,內容img圖片超出解決辦法

uniapp vue v-html,顯示富文字,內容img圖片超出解決辦法

uniapp h5中,v-html,img圖片中style=width:auto;會顯示圖片原來的尺寸,會超出螢幕,替換成width:100%,這樣就不會超出螢幕

重要的地方,例如<img src="https://cdn2.xxkucun.com/xxkucun/tuwen/20200904/1d959815-6a1c-4eb2-93b7-25ff3d6559eb?x-oss-process=style/xptw" data-ratio="1" alt="fca7c67836811c375a66e46fdcbc0ca5.gif" data-w="1" width="353" height="201" style="width: 353px; height: 201px;"/>這種,直接寫死了width,height,這個是真的煩

正則太差,網上也沒有找到合適的案例,只能自己用死辦法解決了

/**
* 去除圖片中的width屬性,height屬性
*
* @param img 圖片字串
* @return 返回去除後的字串
*/
public static String replaceImgWidthHeight(String img) {
// 去掉width屬性
String patternWidth = "width=\"\\d*\"";
Pattern r = Pattern.compile(patternWidth);
Matcher m = r.matcher(img);
while (m.find()) {
img = img.replace(m.group(), "");
}
// 去掉height屬性
String patternHeight = "height=\"\\d*\"";
Pattern rh = Pattern.compile(patternHeight);
Matcher mh = rh.matcher(img);
while (mh.find()) {
img = img.replace(mh.group(), "");
}
// 替換style中的width屬性
String styleWidth = "width:.*?px;";
Pattern sw = Pattern.compile(styleWidth);
Matcher swh = sw.matcher(img);
while (swh.find()) {
img = img.replace(swh.group(), "max-width:100%;");
}
// 替換style中的height屬性
String styleHeight = "height:.*?px;";
Pattern sh = Pattern.compile(styleHeight);
Matcher shh = sh.matcher(img);
while (shh.find()) {
img = img.replace(shh.group(), "height:auto;");
}
return img;
}

/**
* 獲取HTML程式碼中的img標籤,並修改圖片屬性為自適應
* @param str HTML程式碼
* @return
*/
public static String replaceHtmlImgWidthHeight(String str) {
String rg = "<img.*?>";
Pattern compile = Pattern.compile(rg);
Matcher matcher = compile.matcher(str);
while (matcher.find()) {
String img = matcher.group();
str = str.replace(img, StringUtil.replaceImgWidthHeight(img));
}
return str;
}



搞了半天,終於解決了,看效果也確實自適應了,沒有超過螢幕了,搞定之後發現有個好簡單的辦法,直接在view中設定樣式style="width: 100%;overflow: hidden;"
<view style="width: 100%;overflow: hidden;" v-html="product.remark"></view>
超出部分直接隱藏好了,看供應商那邊的App也是這樣做的,有些圖片只顯示了一半,思路很重要啊,一行程式碼超出隱藏,一分鐘解決了,結果寫了半天的正則,正則還是太差了,唉
各位路過的大佬有更好的解決方案,歡迎評論區貼出,好讓我學習學習