改變HTML中的光標問題

改變HTML中的光標問題,我在網上找到這一段代碼,用來改變當前光標位置

HRESULT hr;
CComPtr<IHTMLTxtRange> txtRange;
CComPtr<IHTMLSelectionObject> pSelection;
spDoc->get_selection(&pSelection);
if (pSelection)
{
  CComPtr<IDispatch> pDispRange;
  pSelection->createRange(&pDispRange);
  if (pDispRange)
  {
  hr = pDispRange->QueryInterface(IID_IHTMLTxtRange, (void**)&txtRange);
  if ( SUCCEEDED(hr) && txtRange )
  { 
  txtRange->collapse(VARIANT_TRUE);
  if (pElem)
  {
  if (SUCCEEDED(txtRange->moveToElementText(pElem)))
  { 
  txtRange->select();
  txtRange->scrollIntoView();
  }
  }
  txtRange.Release();
  }
  pDispRange.Release();
  }
  pSelection.Release();  // http://www.wzszf.com/
}

其中,pElem 是指定要跳到的元素(我的情況下,它是一個 <div>&nbsp;</div>,這段代碼可以使光標移到那個元素上,而且那個空位也被選上。但是我衹想要光標移動,不想要文字被選取,我嘗試去掉 txtRange->select() 這一段,但那樣光標又不移動

我是利用 IHTMLDocument2.createElement 來生成新的元素,然後用 IHTMLDOMNode.appendChild插入到指定位置上,插入元素沒有問題。但光標就是移不過去。我後來改用下面的代碼,但還是沒效

HRESULT hr;
CComPtr<IMarkupServices> pMS;
CComPtr<IMarkupContainer> pMarkup;
CComPtr<IMarkupPointer> pPtr;
CComPtr<IDisplayPointer> dpPtr;
CComPtr<IDisplayServices> pDispServices;
CComPtr<IHTMLCaret> spCaret; 

hr = spDoc->QueryInterface(IID_IMarkupContainer, (void **)&pMarkup);
if (hr==S_OK)

  hr = spDoc->QueryInterface(IID_IMarkupServices, (void **)&pMS);
  if (hr==S_OK) 
  { 
  pMS->CreateMarkupPointer(&pPtr);
  hr = spDoc->QueryInterface(IID_IDisplayServices, (void **)&pDispServices);
  if (hr==S_OK)
  { 
  pDispServices->CreateDisplayPointer(&dpPtr);
  pDispServices->GetCaret(&spCaret);
  pMS->CreateMarkupPointer(&pPtr);
  pPtr->MoveAdjacentToElement( pElem, ELEM_ADJ_AfterEnd);
  dpPtr->MoveToMarkupPointer(pPtr, dpPtr);
  spCaret->MoveCaretToPointer(dpPtr, TRUE, CARET_DIRECTION_SAME);
  }
  }
}

上面的代碼中,pElem 是我新插入的元素

實在想不到好辦法,最後衹好用下面這個笨方法

HRESULT hr; 
CComPtr <IHTMLTxtRange> txtRange; 
CComPtr <IHTMLSelectionObject> pSelection; 
spDoc->get_selection(&pSelection); 
if (pSelection) 

  CComPtr <IDispatch> pDispRange; 
  pSelection->createRange(&pDispRange); 
  if (pDispRange) 
  { 
  hr = pDispRange->QueryInterface(IID_IHTMLTxtRange, (void**)&txtRange); 
  if ( SUCCEEDED(hr) && txtRange ) 
  { 
  txtRange->collapse(VARIANT_TRUE); 
  if (pElem) 
  { 
  if (SUCCEEDED(txtRange->moveToElementText(pElem))) 
  { long n;
  txtRange->move(L"character", 1, &n); // 向前進一步
  txtRange->move(L"character", -1, &n); // 然後退回去,這樣就移動了光標 
  txtRange->select(); 
  txtRange->scrollIntoView(); 
  } 
  } 
  txtRange.Release(); 
  } 
  pDispRange.Release(); 
  } 
  pSelection.Release(); 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值