首页 > 解决方案 > 从字符串中获取 xyw?

问题描述

我在javascript中有一个字符串,例如:

"<div class="croppie-result" style="width: 584px; height: 584px;"><img src="screenshot.png" style="left: -391px; top: -92px;"></div>"

我想从变量 , , 中的这个字符串中提取lefttop获取,widthx值。yw

x=391
y=92
w=584

我该怎么做呢?

注意: x 和 y 的值是有意为正的,而不是错误的。

这是裁剪图像或使用croppie.

这是完整的代码:

var el = document.getElementById('resizer-demo');
var resize = new Croppie(el, {
  viewport: {
    width: 300,
    height: 300,
    type: 'square'
  },
  boundary: {
    width: 400,
    height: 400
  },
  showZoomer: true,
  enableResize: false,
  enableOrientation: true,
  mouseWheelZoom: 'ctrl'
});
resize.bind({
  url: '/home/shashanksingh/Pictures/Screenshot.png',
});

//on button click
function myFunction() {
  document.getElementById('msg').innerHTML = 'You clicked!';
  resize.result('html').then(function(data) {

    document.getElementById('msg').innerHTML = data.outerHTML;
    debugger
    // do something with cropped blob
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.min.css" rel="stylesheet" />

<center>
  <div id='resizer-demo'></div>
  <button type="button" id='crop_it' onclick='myFunction()'>Crop</button>
  <div id='msg'>You can also use CTRL + mouse-wheel to zoom.</div>
  <br><br><br>
</center>

对我必须提出服务器请求的建议持开放态度。我正在考虑发送这些坐标,因为我无能为力。

标签: javascriptregexstringcroppie

解决方案


https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

这是初学者非常基本的方法。您可以轻松className获得Div

  1. 通过类名获取 div 元素。

  2. 开始width使用style.width

  3. 从元素中获取'img'childElement 。div

  4. 从childElement获取style.left和获取。style.top'img'

  5. Integer使用parseInt()和获取Math.abs()正值。

var y = document.getElementsByClassName('croppie-result')[0];
var widthValue= parseInt(y.style.width, 10);
var leftValue= Math.abs(parseInt(y.getElementsByTagName('img')[0].style.left, 10));
var topValue= Math.abs(parseInt(y.getElementsByTagName('img')[0].style.top,10));
console.log("w =", widthValue);
console.log("x =", leftValue);
console.log("y =", topValue);
<div class="croppie-result" style="width: 584px; height: 584px;"><img src="screenshot.png" style="left: -391px; top: -92px;"></div>


推荐阅读