我有一个滚动动画,想获得到给定时间的过渡值。
const transform = document.getElementsByClassName('slideContainer')[0].style.transform;
例如,我得到以下值:translate(-2.51028%, 0%) translate3d(0px, 0px, 0px)
但是我只想要-2.51028%
我该怎么做?
答案 0 :(得分:4)
您可以使用translate(
:
const transform = 'translate(-2.51028%, 0%) translate3d(0px, 0px, 0px)';
const match = transform.match(/translate\(([^,]+)/);
// match[0] refers to the entire matched substring,
// match[1] will contain the first captured group:
console.log(match[1]);
答案 1 :(得分:1)
像您可能想要使用正则表达式的声音-它们是匹配字符串模式的好工具。您可以匹配字符串的开头,后跟Dictionary
,然后在组中捕获尽可能多的非逗号字符。该组将具有您想要的子字符串:
// Dictionary.Item property we will use to get/set values
var itemProp = target.GetType().GetProperty("Item");
// Since you want to modify dictionary while enumerating it's items (which is not allowed),
// you have to use .Cast<object>().ToList() to temporarily store all items in the list
foreach (var item in (target as IEnumerable).Cast<object>().ToList())
{
// item is of type KeyValuePair<TKey,TValue> and has Key and Value properties.
// Use reflection to read content from the Key property
var itemKey = item.GetType().GetProperty("Key").GetValue(item);
Action<Object> valueSetter = (val) => itemProp.SetValue(target, val, new object[] { itemKey });
// valueSetter(someNewValue);
// It's not possible to just change the key of some item. As a workaround,
// you have to remove original item from the dictionary and insert a new item
// with the original value and with a new key.
Action<Object> keySetter = (key) =>
{
// read value from the dictionary for original key
var val = itemProp.GetValue(target, new object[] { itemKey });
// set this value to the disctionary with the new key
itemProp.SetValue(target, val, new object[] { key });
// remove original key from the Dictionary
target.GetType().GetMethod("Remove").Invoke(target, new Object[] { itemKey });
// need to "remember" the new key to allow the keySetter to be called repeatedly
itemKey = key;
};
// keySetter(someNewKey);
}